我正在尝试制作一个在访问 Facebook 时激活的扩展程序。到目前为止,一切都很好,但是随后它开始无限期地运行我的代码。
我想要的是仅在我第一次访问 Facebook 时运行 content.js 脚本,然后不再运行它。
我目前的方法是这样的,但它不起作用:
背景.js
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.storage) {
if (typeof request.value != 'undefined') {
localStorage[request.storage] = request.value;
}
sendResponse({storage: localStorage[request.storage]});
} else {
sendResponse({});
}
});
内容.js
var status;
chrome.extension.sendRequest({storage: 'status'}, function(response) {
status = response.storage;
});
if(status != '1')
{
chrome.extension.sendRequest({storage: 'status', value: '1'});
// do my stuff here but only 1 time
}
list .json
"content_scripts": [ {
"js": [ "js/jquery.js", "content.js" ],
"matches": [ "https://facebook.com/" ]
} ],
基本上我的想法是在访问 Facebook 时运行 content.js,然后在脚本完成后,添加一个状态变量,然后下次检查状态是否为 1,这意味着代码之前已经运行过。
我怎样才能做到这一点?
谢谢。
最佳答案
1) 您正在制作 the standard async JavaScript mistake .
var status;
chrome.extension.sendRequest({storage: 'status'}, function(response) {
status = response.storage; // <--+
}); // | This code didn't execute yet
// |
if(status != '1') // --------------+
{
chrome.extension.sendRequest({storage: 'status', value: '1'});
// do my stuff here but only 1 time
}
2) 您正在使用一个非常old and deprecated Messaging 的版本。 extension.sendRequest
/onRequest
需要去掉,替换为 runtime.sendMessage
/onMessage
。
3) 最好不要在这里使用消息传递; chrome.storage
API是专门为此目的而制作的。同样,也许您正在使用一些非常古老的教程。
关于javascript - 仅运行一次的 Chrome 扩展程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31501765/