从弹出页面到内容脚本页面的通信
我正在开发一个扩展,但我不想使用选项页面。我使用浏览器操作(图标出现在右上角),通过该页面进行一些首选项,并将它们存储在 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.
});
});
content.js
$(document).ready(function(){
var p;
chrome.extension.sendRequest({method: "getList"}, function(response) {
p = response.status;
alert(response.status);
});
});
I am developing an extension and I do not wish to use the options page. I use a browser action (the icon appears on the top-right), and some preferences are made trough that page and I store them in localStorage.
However, my content script needs to read that localStorage but I know that it cannot access it. I looked the message passing but could not accomplish what I would wanted.
Here what I have tried:
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.
});
});
content.js
$(document).ready(function(){
var p;
chrome.extension.sendRequest({method: "getList"}, function(response) {
p = response.status;
alert(response.status);
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
弹出窗口是短暂的,这意味着代码仅在弹出窗口打开时有效。这意味着您的听众将会丢失。
将侦听器的代码从 popup.html 移至后台页面,那么这应该可以正常工作。
The popup is ephemeral meaning that the code only lives for the time that the popup is open. This means that your listener will be lost.
Move the code for your listener from your popup.html in to a background page, then this should work fine.