通过Chrome扩展程序访问Cookie

时间:2014-01-01 19:51:56

标签: google-chrome cookies google-chrome-extension

我想编写一个Chrome扩展程序,可以在某些页面上显示某些内容,具体取决于我网站设置的Cookie值。但是,我的扩展只是拒绝承认chrome.cookies对象的存在(是的,我在权限列表中包含“cookies”)。 我通过在内容脚本中添加以下代码来测试它:

$(document).ready(function() {
    console.log (chrome.cookies);
});

它总是打印“未定义”,我不知道为什么。 我应该注意一些使用限制,或者我错过了一些其他必要的细节吗?

1 个答案:

答案 0 :(得分:2)

最终我明白了......

在内容脚本中:

chrome.extension.sendRequest("getID", function(response) {
    // do something with the id
});

在后台脚本中:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if (request == 'getID') {
        chrome.cookies.getAll ({domain: 'whatever', name: 'id'}, function (cookies) {
            sendResponse (cookies[0].value);
        });
    }
});
相关问题