Why is chrome.cookies undefined in a content script?

早过忘川 提交于 2019-12-18 16:11:06

问题


Whenever I try to read from a cookie using the chrome.cookies.get() function I get this error:

TypeError: Cannot read property 'get' of undefined.

I am calling the function in my content.js file, and it will only run on twitter.com(that part works).

Here is my manifest file:

{
  "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"
  }
}

Here is my content.js (it always alerts on the twitter page so that works fine):

$(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
    }
})

回答1:


Quoting the docs about content scripts:

[Content scripts cannot] Use chrome.* APIs (except for parts of chrome.extension)

So, to use chrome.cookies API, you need to do so from a background page, communicating with the content script if needed.



来源:https://stackoverflow.com/questions/23038032/why-is-chrome-cookies-undefined-in-a-content-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!