Google chrome extension 从弹出页面到内容脚本页面的通信

Google chrome extension 从弹出页面到内容脚本页面的通信,google-chrome-extension,message-passing,Google Chrome Extension,Message Passing,我正在开发一个扩展,我不希望使用选项页面。我使用浏览器操作(图标显示在右上角),一些首选项是通过该页面创建的,我将它们存储在localStorage中 但是,我的内容脚本需要读取该本地存储,但我知道它无法访问它。我看着信息传递,但无法实现我想要的 以下是我尝试过的: popup.js $(document).ready(function(){ chrome.extension.onRequest.addListener(function(request, sender, sendResp

我正在开发一个扩展,我不希望使用选项页面。我使用浏览器操作(图标显示在右上角),一些首选项是通过该页面创建的,我将它们存储在localStorage中

但是,我的内容脚本需要读取该本地存储,但我知道它无法访问它。我看着信息传递,但无法实现我想要的

以下是我尝试过的:

popup.js

$(document).ready(function(){
    chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
        if (request.method == "getList")
            sendResponse({status: localStorage['list']});
        else
            sendResponse({}); // snub them.
        });
});
$(document).ready(function(){
    var p;
    chrome.extension.sendRequest({method: "getList"}, function(response) {
        p = response.status;
        alert(response.status);
    });
});
content.js

$(document).ready(function(){
    chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
        if (request.method == "getList")
            sendResponse({status: localStorage['list']});
        else
            sendResponse({}); // snub them.
        });
});
$(document).ready(function(){
    var p;
    chrome.extension.sendRequest({method: "getList"}, function(response) {
        p = response.status;
        alert(response.status);
    });
});

弹出窗口是短暂的,这意味着代码只在弹出窗口打开时有效。这意味着你的听众将迷失方向


将侦听器的代码从popup.html移到a,这样就可以了。

我注意到了差异,谢谢。我从popup->background->localStorage->contentscript建立了一个连接。您可以通过后台脚本跟踪默认弹出窗口中存在的按钮的onclick事件吗?