【问题标题】:Why is chrome.cookies undefined in a content script?为什么 chrome.cookies 在内容脚本中未定义?
【发布时间】:2014-05-27 02:39:31
【问题描述】:

每当我尝试使用 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
    }
})

【问题讨论】:

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


    【解决方案1】:

    引用docs about content scripts

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

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

    【讨论】:

    • 那么我将如何实现它,以便当用户打开 Twitter 时它会得到 cookie?
    • @Oxygen- API 暗示无需打开 Twitter 即可查询 cookie。它们与特定的 URL 相关联,而不是实际打开的选项卡。您需要添加一个后台脚本,您可以随时从那里查询。
    • 哦,好点,但我只想在 Twitter 页面加载时读取 cookie,然后能够从 twitter 页面上抓取一些信息。关于如何在后台脚本中实现的任何想法?
    • @Oxygen- 你可以同时拥有。后台中与 Cookie 相关的内容,在 Twitter 中加载的内容脚本,并使用用户导航到的 sendMessage 向后台发出信号。
    • 什么是“后台脚本”?
    【解决方案2】:

    如果有人跳过了这一点,请务必将“cookies”添加到权限中。

    【讨论】:

      猜你喜欢
      • 2017-04-21
      • 1970-01-01
      • 1970-01-01
      • 2017-08-05
      • 2015-03-15
      • 2013-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多