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

Mus*_*afa 2 message-passing google-chrome-extension

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

但是,我的内容脚本需要读取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.
        });
});
Run Code Online (Sandbox Code Playgroud)

content.js

$(document).ready(function(){
    var p;
    chrome.extension.sendRequest({method: "getList"}, function(response) {
        p = response.status;
        alert(response.status);
    });
});
Run Code Online (Sandbox Code Playgroud)

Kin*_*lan 6

弹出窗口是短暂的,意味着代码仅在弹出窗口打开时存在.这意味着您的听众将会迷失.

将您的监听器代码从popup.html移动到后台页面,然后这应该可以正常工作.

  • 我注意到了差异,谢谢.我从popup-> background-> localStorage-> contentScript建立了连接 (2认同)