繁体   English   中英

记住状态镀铬扩展

[英]Remember state chrome extension

我使用chrome扩展来触发两个内容脚本来注入css。 如果用户打开页面,则加载contentscript-on.js(在我的manifest.json中定义):

的manifest.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 
});

一切正常,但我怎样才能保存图标的“状态”? 如果用户关闭浏览器并再次打开它,则应加载上次使用的内容脚本。

非常感谢您的帮助。

你有两种方法(至少),一种是“旧”,一种是“新”。

  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上下文对于内容脚本是不同的,因此他们需要通过Messaging进行通信以从后台脚本中获取值; 此外,如果在隐身模式下使用扩展程序,也会出现复杂情况。

  2. 新增功能: chrome.storage API

    要使用新方法,您需要在清单中使用"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);
        });
      });
    });

这样,您只需要一个内容脚本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM