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

disbfnqx  于 2023-01-28  发布在  Go
关注(0)|答案(5)|浏览(180)

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

TypeError: Cannot read property 'get' of undefined.

我在content.js文件中调用这个函数,它只能在www.example.com上运行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
    }
})
c2e8gylq

c2e8gylq1#

引用docs about content scripts
[内容脚本无法]使用chrome. * API(chrome. extension的部分除外)
因此,要使用chrome.cookies API,需要从后台页面执行此操作,如果需要,可以与内容脚本通信。

a0zr77ik

a0zr77ik2#

如果有人跳过了这一步,请确保将“cookie”添加到权限中。

uujelgoq

uujelgoq3#

根据jbodily的回答,缺少的部分正在添加

"permissions": ["activeTab", "cookies"],

到舱单

jdg4fx2g

jdg4fx2g4#

除上述指定的“权限”外,还必须包括“host_permissions”,如下所示:

...,
host_permissions: ["https://google.com", "http://localhost"],
....
nx7onnlm

nx7onnlm5#

我作为一个规范来回答这个问题,因为"manifest_version": 2,现在已经过时了。
下面是一个简单的扩展,展示了如何从内容、后台和弹出窗口脚本中获取cookie。
manifest.json

{
  "manifest_version": 3,
  "name": "Show cookie",
  "version": "1.0.0",
  "description": "Extension to show cookies",
  "author": "g",
  "action": {
    "default_popup": "popup.html",
    "default_title": "Show cookies"
  },
  "background": {
    "service_worker": "background.js"
  },
  "permissions": [
    "cookies",
    "scripting",
    "tabs"
  ],
  "content_scripts": [
    {
      "run_at": "document_start",
      "matches": [
        "http://*/*",
        "https://*/*",
        "<all_urls>"
      ],
      "js": [
        "content.js"
      ],
      "css": [
        "content.style.css"
      ]
    }
  ],
  "host_permissions": [
    "https://*/*"
  ]
}

background.js

// visible in the extension's devtools console
console.log("background:", chrome.cookies);

content.js

document.addEventListener("DOMContentLoaded", event => {

  // visible in the webpage's devtools console
  console.log("content script:", document.cookie);

  // visible in the webpage's DOM
  const p = document.createElement("p");
  document.body.prepend(p);
  p.classList.add("cookie");
  p.textContent = document.cookie;
});

popup.html

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Show cookie extension</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
  <h3>Cookie</h3>
  <div>loading...</div>
  <script src="popup.js"></script>
</body>
</html>

popup.js

// https://stackoverflow.com/a/46870005/6243352
async function getCookie(tabId) {
  const [{result}] = await chrome.scripting.executeScript({
    func: () => document.cookie,
    args: [],
    target: {
      tabId: tabId ??
        (await chrome.tabs.query({active: true, currentWindow: true}))[0].id
    },
    world: "MAIN",
  });
  return result;
}

(async () => {
  const cookie = await getCookie();

  // visible in the extension's devtools console
  console.log("popup:", cookie);

  // visible in the extension's DOM
  document.querySelector("div").textContent = cookie;
})();

相关问题