如何使用backgroundpage保留在注入js中使用的值?

How to use backgroundpage to stay a value which used in an inject js?

{  
    "name": "coffee",
    "manifest_version":2,
    "version": "1.0",  
    "description": "coffee test",  
    "browser_action": {  
       "default_icon": "icon.png" ,
       "default_title": "My Task List",
        "default_popup": "popup.html"
     },
  "background": {
    "scripts": ["background.js"]
  },
     "content_scripts": [{
         "matches": ["http://*/*","https://*/*" ], 
         "js": ["inject.js"], 
         "run_at": "document_end",
         "all_frames": true 
    }],
    "permissions": [   
     "tabs", "http://*/*","https://*/*"  
    ]   
}

manifest.josn

count=1;

background.js

var bgpg=chrome.extension.getBackgroundPage();
if(bgpg)
{
    alert("ok");
    if(bgpg.count>=0){
        bgpg.count=bgpg.count+1;
    }else{
        bgpg.count=0;
    }
    alert(bgpg.count);

}else{alert("NO");}

inject.js.

并没有改变anything.In事实上,上周我成功地使用了背景值,但是今天我完全找不到错误的地方。

内容脚本无法调用 chrome.extension.getBackgroundPage(),权限太高了。

出于安全原因内容脚本have very limited access to Chrome APIs。后台页面具有完全访问权限,因此禁止直接操作它。您的代码抛出错误并停止。

However, content scripts have some limitations. They cannot:

  • Use chrome.* APIs, with the exception of:
    • extension ( getURL , inIncognitoContext , lastError , onRequest , sendRequest )
    • [...]

您将需要使用 Messaging to communicate with the background page; however, if all you need is some data you can try using chrome.storage - 两者共享。