在Chrome扩展程序中访问background.js中的用户选项

时间:2018-10-17 20:00:33

标签: javascript google-chrome-extension

我正在尝试访问chrome.storage.sync,我在其中将一些用户选项存储在background.js中,但是chrome.storage.sync.get的异步特性导致了我的问题。

如果我尝试在chrome.webRequest.onBeforeRequest.addListener中使用chrome.storage.sync.get,则回调函数的使用速度不够快。

我尝试将用户选项添加为background.js中的全局变量,但是在我看来,该值不会持久。

还有其他人在background.js中使用用户选项吗?

function getoption(){
  chrome.storage.sync.get({
    radarpref: 'nothing',
  }, function(items) {
  console.log(items.radarpref);
  return items.radarpref;
    
  });

}
var hold = getoption();
console.log (hold) //this returns hold value

chrome.webRequest.onBeforeRequest.addListener(
  function(info) {

    //this doesn't work - yet
   console.log('i dont see the hold');
	console.log(hold) //hold not returned when callback ran
  ...
  

1 个答案:

答案 0 :(得分:2)

如果您需要同步使用任何异步存储中的设置-最好的方法是对其进行缓存。

您需要在background.js开始时将设置加载到缓存中,然后每次触发chrome.storage.onChanged事件时都需要更新缓存。

示例操作方法:

manifest.js

{
    "manifest_version": 2,
    "name": "Settings Online demo",
    "description": "Settings Online demo",    
    "applications": {
        "gecko": {
            "id": "852a5a44289192c3cd3d71e06fdcdb43b1437971@j2me.ws"
        }
    },
    "version": "0.0.1",
    "background": {
        "scripts": ["background.js"]
    },
    "permissions": [
        "storage",
        "webRequest",
        "webRequestBlocking",
        "<all_urls>"
    ],
    "options_ui": {
        "page":"properties.html",
        "chrome_style": true
    }
}

请注意,如果您需要在firefox上使用它,则需要具有非临时的应用程序ID。<all_urls>权限需要获得对任何URL请求处理的访问权限。

background.js

((storage) => {
    let settings = (function(properties) {

        // Save settings
        this.set = (properties,ok) => {
            for(key in properties || {}){
                this[key]=properties[key];
            }
            storage.set(
                properties
            ,() => {
                ok(settings);
            });
        };

        //Default values processing
        for(key in properties || {}){
            this[key]=properties[key];
        }

        // Initial settings read
        storage.get(properties,(properties) => {
            for(key in properties){
                this[key]=properties[key];
            }
        });


        // Listen settings change and cache it
        chrome.storage.onChanged.addListener((msg) => {
            for(key in msg){
                this[key]=msg[key].newValue;
            }
        });

        return this;
    }).call({},{"property":"default","name":"me"})

    chrome.webRequest.onBeforeRequest.addListener(
      function(info) {
       // Update and persist settings
       settings.set({"lastRequest":info},()=>{console.log("Settings saved")});
       console.log('Catch', settings.name,settings.property);
    },{urls:["https://*/*"]});
})(chrome.storage.sync || chrome.storage.local);

请注意,我使用chrome.storage.sync || chrome.storage.local是因为某些浏览器(Opera,移动浏览器)不支持同步存储,但是支持本地存储。

然后在属性页上查看如何处理属性更改: properties.html

<html>
    <head>
        <script src="properties.js" type="text/javascript"></script>
    </head>
    <body>
        <label>Property:<input id="property" type="text"></label>
        <input id="save-properties" value="save" type="submit">
    </body>
</html>

properties.js

((storage) => {
    let saveOptions = () => {
        let property = document.getElementById("property").value;

        storage.set({
            "property": property
        },() => {
            window.close();
        });
    }

    let restoreOptions = () => {
        storage.get({
            "property": "default"
        }, (properties) => {
            document.getElementById("property").value = properties.property;
        });
        document.getElementById("save-properties").addEventListener("click", saveOptions);
    }
    document.addEventListener("DOMContentLoaded", restoreOptions);
})(chrome.storage.sync || chrome.storage.local);

仅此而已:)

PS>此解决方案有一个弱点:如果您的应用程序对设置敏感,并且不能使用默认设置,或者您需要确保在启动时使用自定义设置-您需要延迟后台。 js在未加载设置的情况下启动。您可以使用回调或Promise:

background.js-等待设置被回调加载

((storage) => {
    let settings = (function(properties) {

        // Update settings
        this.set = (properties,ok) => {
            for(key in properties || {}){
                this[key]=properties[key];
            }
            storage.set(
                properties
            ,() => {
                ok(settings);
            });
        };

        //Default values processing
        for(key in properties || {}){
            this[key]=properties[key];
        }

        // Listen settings change and cache it
        chrome.storage.onChanged.addListener((msg) => {
            for(key in msg){
                this[key]=msg[key].newValue;
            }
        });

        // Initial settings read
        storage.get(properties,(properties) => {
            for(key in properties){
                this[key]=properties[key];
            }
            mainLoop();
        });

        return this;
    }).call({},{"property":"default","name":"me"})

    let mainLoop = () => {

        //.. all you settings-sensitive code
        chrome.webRequest.onBeforeRequest.addListener(
          function(info) {
            // Update settings and persist it       
            settings.set({"lastRequest":info},()=>{console.log("Settings saved")});
           console.log('Catch', settings.name,settings.property);
        },{urls:["https://*/*"]});
    };

})(chrome.storage.sync || chrome.storage.local);

background.js-等待设置加载承诺时

((storage) => {
    let settings = ((properties) => {

        this.set = (properties) => {
            for(key in properties || {}){
                this[key]=properties[key];
            }
            return new Promise((ok,err) => {
                storage.set(
                    properties
                ,() => {
                    ok(settings);
                });
            });
        };

        return new Promise((ok,err) => {
            //Default values processing
            for(key in properties || {}){
                this[key]=properties[key];
            }

            // Listen settings change and cache it
            chrome.storage.onChanged.addListener((msg) => {
                for(key in msg){
                    this[key]=msg[key].newValue;
                }
            });

            // Initial settings read
            storage.get(properties,(properties) => {
                for(key in properties){
                    this[key]=properties[key];
                }
                ok(this);
            });
        });
    }).call({},{"property":"default","name":"me"}).then((settings) => {
        //.. all you settings-sensitive code

        chrome.webRequest.onBeforeRequest.addListener(
          function(info) {
            // Update settings and persist it       
            settings.set({"lastRequest":info}).then(()=>{console.log("Settings saved")});
            console.log('Catch', settings.name,settings.property);
        },{urls:["https://*/*"]});
    }).catch(()=>{});

})(chrome.storage.sync || chrome.storage.local);

了解详情

  1. 存储规格/ Firefox: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage
  2. 存储点/ chrome:https://developer.chrome.com/apps/storage
  3. 权限请求/ Firefox: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Request_the_right_permissions