javascript getAll返回一个空数组

kt06eoxx  于 2023-04-19  发布在  Java
关注(0)|答案(4)|浏览(96)

我正在开发一个简单的chrome扩展,它可以一键删除域中的所有cookie,但由于某种原因,它不起作用。当我试图从域中获取所有cookie时,它返回一个空数组。我做错了什么?下面是js脚本:

$("#fixTheCookiesButton").click(() => {
  // delete the cookies
  chrome.cookies.getAll({domain: "https://www.youtube.com"}, (cookies) => {
    console.log("deleting " + cookies.length + " cookies")
    for(var i = 0; i < cookies.length; i++){
      console.log(i + " deleted")
      chrome.cookies.remove({
        url: "https://www.youtube.com" + cookies[i].path,
        name: cookies[i].name
      })
    }
    
    // some other stuff that isn't relevant here
}

这是我的货单

{
  "manifest_version": 2,
  "name": "FixYT",
  "version": "1.0",
  "description": "Fixes that YT cookie bug with one click",
  "browser_action": {
          "default_title": "FixYT",
          "default_popup": "popup.html"
  },
  "permissions": [
    "cookies",
    "https://www.youtube.com/",
    "*://www.youtube.com/",
    "tabs",
    "*://*/"
  ]
}

我试着在互联网上寻找,但我找不到任何解决方案。

5f0d552i

5f0d552i1#

正如伊萨所说,chrome.cookies只在background.js中定义
添加到manifest,以便我们可以访问background.js中的chrome. cookie

 "permissions": [
      ...
       "cookies",
     ],

background.js

...
chrome.cookies.getAll({
    }, function (theCookies) {
        cookies = theCookies
        console.log(cookies)
    });

从background.js向其他视图发送Cookie

(不需要,但仍然有用)

添加到panel.js以搜索cookie。[当您打开扩展ie(拼图图标)-〉单击您的扩展时,将触发]

chrome.runtime.sendMessage({ command: "GetCookies"}, 
      function(response) {
            console.log("I received cookies!")
            console.log(response)
      }
);

添加到background.js逻辑以从浏览器获取cookie并检查已知cookie

chrome.runtime.onMessage.addListener(function (message, sender, callback) {
    if (message.command === 'GetCookies') {
        checkKnownCookies()
    }
});
let cookies = [] // Hold IDs of recognized cookies
function checkKnownCookies() {
    chrome.cookies.getAll({
    }, function (theCookies) {
        cookies = theCookies
        console.log(cookies)
        callback(theCookies)
    });
}
 

https://developer.chrome.com/docs/extensions/reference/cookies/#method-getAll
要查看background.js的控制台,请转到(拼图图标)-〉管理扩展,然后单击扩展的background.html的href链接

ukxgm1gy

ukxgm1gy2#

你应该在background.js中调用这个代码块

chrome.cookies.getAll({
  domain: ".youtube.com"
}, function (cookies) {
  for (var i = 0; i < cookies.length; i++) {
    console.log(cookies[i] + "deleted");
    chrome.cookies.remove({
      url: "https://" + cookies[i].domain + cookies[i].path,
      name: cookies[i].name
    });
  }
});
yv5phkfx

yv5phkfx3#

permissionshost_permissions都是必需的。

"permissions": [
  "cookies",
  "tabs"
],
"host_permissions": ["<all_urls>"],
cgyqldqp

cgyqldqp4#

这是一个将cookie从service worker传递到内容脚本的更现代的示例,根据当前的指导方针,该脚本使用promise而不是回调。您必须使用manifest版本3或更高版本才能使用此方法。

content_script.js

chrome.runtime.sendMessage({ action: 'getCookies', domain: document.domain })
    .then(response => {
        if (response.success) {
            // Construct the cookie header string
            const cookieHeader = response.cookies.map(cookie => `${cookie.name}=${cookie.value}`).join('; ');

            // Make a fetch request with the cookies included
            fetch('/some/path', {
                headers: {Cookie: cookieHeader}
            })

        } else {
            console.log('Error: ' + response.error)
        }
    })

service_worker.js

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {

// getCookies
if (message.action === 'getCookies') {
    // Get all cookies for this domain
    chrome.cookies.getAll({ domain: message.domain }, cookies => {
        if (chrome.runtime.lastError) {
            // Handle any errors
            sendResponse({ success: false, error: chrome.runtime.lastError });
        } else {
            // Return the cookies in the response message
            sendResponse({ success: true, cookies: cookies });
        }
    });

    // Return true to indicate that we will send a response asynchronously
    return true;
}

});

相关问题