1

chrome 拡張機能を使用して 2 つのコンテンツ スクリプトを起動し、css を挿入します。ユーザーがページを開くと、contentscript-on.js が読み込まれます (私の manifest.json で定義されています):

マニフェスト.json

{
    "name": "tools",
    "version": "1.1",
    "description": "tools",
    "browser_action": {
        "default_icon": "icon-on.png",
        "default_title": "tools"
    },
    "manifest_version": 2,
    "content_scripts": [
        {
            "matches": [ "*://*/*" ],
            "include_globs": [ "*://app.example.*/*" ],
            "js": ["jquery-1.11.0.min.js", "contentscript-on.js"]
        }
    ],
    "background": {
        "scripts": ["background.js"],
        "persistent": true
    },
    "permissions": [
        "storage",
        "https://*.app.example.de/*", "tabs", "webNavigation"
    ]   
}

background.js

function getToggle(callback) { // expects function(value){...}
  chrome.storage.local.get('toggle', function(data){
    if(data.toggle === undefined) {
      callback(true); // default value
    } else {
      callback(data.toggle);
    }
  });
}

function setToggle(value, callback){ // expects function(){...}
  chrome.storage.local.set({toggle : value}, function(){
    if(chrome.runtime.lastError) {
      throw Error(chrome.runtime.lastError);
    } else {
      callback();
    }
  });
}

chrome.browserAction.onClicked.addListener( function(tab) {
  getToggle(function(toggle){
    toggle = !toggle;
    setToggle(toggle, function(){
      if(toggle){
    //change the icon after pushed the icon to On
    chrome.browserAction.setIcon({path: "icon-on.png", tabId:tab.id});
    //start the content script to hide dashboard
    chrome.tabs.executeScript({file:"contentscript-on.js"});
  }
  else{

    //change the icon after pushed the icon to Off
    chrome.browserAction.setIcon({path: "icon-off.png", tabId:tab.id});
    //start the content script to hide dashboard
    chrome.tabs.executeScript({file:"contentscript-off.js"});
  }
    });
  });
});  

contentscript-on.js

$(document).ready(function() {

    chrome.storage.local.get('toggle', function(data) {
        if (data.toggle === false) {
            return;
        } else {
            // do some css inject
        }
    });

});

contentscript-off.js

$(document).ready(function() {
  // set css to original 
});

すべて正常に動作しますが、アイコンの「状態」を保存するにはどうすればよいですか? ユーザーがブラウザを閉じて再度開くと、最後に使用した contentscript が読み込まれます。

ご助力ありがとうございます。

4

1 に答える 1

4

(少なくとも) 2 つの方法があり、1 つは「古い」方法で、もう 1 つは「新しい」方法です。

  1. 年:localStorage

    拡張ページは、localStorage読み取り/書き込みが可能な共通のオブジェクトを共有し、ブラウザーの再起動後も永続的です。

    それとの作業は同期的です:

    var toggle;
    if(localStorage.toggle === undefined){
      localStorage.toggle = true;
    }
    toggle = localStorage.toggle;
    
    chrome.browserAction.onClicked.addListener( function(tab) {
      var toggle = !toggle;
      localStorage.toggle = toggle;
      /* The rest of your code; at this point toggle is saved */
    });
    

    操作は簡単ですが、欠点もあります。localStorageコンテンツ スクリプトではコンテキストが異なるため、バックグラウンド スクリプトから値を取得するにはメッセージング経由で通信する必要があります。また、拡張機能をシークレット モードで使用すると複雑になります。

  2. 新規: chrome.storageAPI

    新しいメソッドを使用する"storage"には、マニフェストでアクセス許可が必要です (警告は生成されません)。

    また、 とは異なりlocalStorage、それでの作業は非同期です。つまり、コールバックを使用する必要があります。

    function getToggle(callback) { // expects function(value){...}
      chrome.storage.local.get('toggle', function(data){
        if(data.toggle === undefined) {
          callback(true); // default value
        } else {
          callback(data.toggle);
        }
      });
    }
    
    function setToggle(value, callback){ // expects function(){...}
      chrome.storage.local.set({toggle : value}, function(){
        if(chrome.runtime.lastError) {
          throw Error(chrome.runtime.lastError);
        } else {
          callback();
        }
      });
    }
    
    chrome.browserAction.onClicked.addListener( function(tab) {
      getToggle(function(toggle){
        toggle = !toggle;
        setToggle(toggle, function(){
          /* The rest of your code; at this point toggle is saved */
        });
      });
    });
    

    非同期コードを扱うのは少し難しくなりますが、いくつかの利点があります。つまり、コンテンツ スクリプトchrome.storageは親と通信する代わりに直接使用できonChanged、 で変更を監視でき、chrome.storage.sync代わりに (または一緒に)使用chrome.storage.localして、ユーザーがログインしているすべてのブラウザーに変更を伝達できます。

編集

OPがタブごとの状態とグローバル状態を混在させるのを間違えたため、完全なソリューションを含めています。

contentscript.js

$(document).ready(function() {
  chrome.storage.local.get('toggle', function(data) {
    if (data.toggle === false) {
      return;
    } else {
      /* do some css inject */
    }
  });

  chrome.storage.onChanged.addListener(function(changes, areaName){
    if(areaName == "local" && changes.toggle) { 
      if(changes.toggle.newValue) {
        /* do some css inject */
      } else {
        /* set css to original */
      }
    }
  });
});

background.js:

    /* getToggle, setToggle as above */

    function setIcon(value){
      var path = (value)?"icon-on.png":"icon-off.png";
      chrome.browserAction.setIcon({path: path});
    }

    getToggle(setIcon); // Initial state

    chrome.browserAction.onClicked.addListener( function(tab) {
      getToggle(function(toggle){
        setToggle(!toggle, function(){
          setIcon(!toggle);
        });
      });
    });

このように、必要なコンテンツ スクリプトは 1 つだけです。

于 2014-04-28T12:25:53.837 に答える