为什么chrome.cookies在内容脚本中未定义?

时间:2014-04-13 01:17:49

标签: google-chrome google-chrome-extension content-script

每当我尝试使用chrome.cookies.get()函数读取cookie时,我都会收到此错误:

TypeError: Cannot read property 'get' of undefined.

我在我的content.js文件中调用该函数,它只能在twitter.com上运行(该部分有效)。

这是我的清单文件:

{
  "manifest_version": 2,

  "name": "Twitter-MultiSignin",
  "description": "twiter sign in",
  "version": "1.0",
  "permissions": [ "cookies", "alarms" , "http://*/*", "https://*/*", "storage"],
  "content_scripts": [{
    "matches": ["http://twitter.com/*","https://twitter.com/*"],
    "js": ["jquery.js","content.js"]
  }],
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  }
}

这是我的content.js(它总是在twitter页面上提醒,以便工作正常):

$(function() {
    alert('got here');
    try{
        chrome.cookies.get({ url: 'https://twitter.com', name: 'auth_token' }, function (cookie){
            alert(cookie.value);
        });
    }catch(err){
        //do nothing
        alert(err);
    }
    try{
        chrome.cookies.get({ url: 'https://twitter.com', name: 'twid' },
        function (cookie) {
            if (cookie) {
              twid_raw = cookie.value;
              twid = twid_raw.split('=')[1]
              alert(twid);
            }
            else{
                alert("not found");
            }
        });
    }catch(err){
        //do nothing
    }
})

2 个答案:

答案 0 :(得分:13)

引用docs about content scripts

  

[内容脚本不能]使用chrome。* API(chrome.extension的部分除外)

因此,要使用chrome.cookies API,您需要从后台页面执行此操作,并在需要时与内容脚本进行通信。

答案 1 :(得分:0)

万一有人跳过此操作,请确保将“ cookies”添加到权限中。