簡體   English   中英

通過Chrome擴展程序檢查Cookie是否存在

[英]Checking if a cookie exists via chrome extension

清單摘錄:

 "permissions": [
    "tabs",
    "cookies",
    "*://*/*"
   ]

我在Popup.js上嘗試過的代碼(無效):

function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
}
else
{
    begin += 2;
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
    end = dc.length;
    }
}
return unescape(dc.substring(begin + prefix.length, end));
} 


function doSomething() {
var myCookie = getCookie("TestCookie");

if (myCookie == null) {
document.write("<p>unable to load</p>");
throw "stop execution";
}
else {
document.write("<p>loaded</p>");
    // do cookie exists stuff
}
}

我不確定chrome擴展程序不支持完整的Java。 我該如何處理這種情況?

根據您的問題,您尚不清楚要獲取哪些Cookie。 如果在擴展名中設置cookie,則可以通過document.cookie對其進行訪問,但這不是在擴展名中保存持久性信息的正確方法,因為存在諸如localStoragechrome.storage類的更好的東西。 但是,如果您需要擴展站點cookie,最好的方法是這樣的:

chrome.cookies.get({ url: 'http://example.com', name: 'somename' },
  function (cookie) {
    if (cookie) {
      console.log(cookie.value);
    }
    else {
      console.log('Can\'t get cookie! Check the name!');
    }
});

不要忘記在清單中包含權限:

"permissions": [
  "cookies",
  "*://*.example.com/*"
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM