Chrome扩展:如何使后台等待执行
Chrome Extension: How to make background wait executescript?
我最近开始开发我的第一个谷歌Chrome扩展,遇到了一个问题。在我的background.js脚本中,我每秒调用script.js script.js: background.js: 因此,我需要每次调用脚本的最大值(1秒,在前一个executeScript之后)。它应该以这种方式工作: 提前感谢您的帮助。/* Some code */
if (condition1) {
setTimeout(func1, 500);
result = 1;
} else
if (condition2) {
setTimeout(func2, 4000);
result = 2;
} else
/*Some code */
result
function func() {
chrome.tabs.executeScript(null, {file: 'script.js'},
function (result) {
console.log(result[0]);
}
);
/* Some code using results of scipt.js */
};
var interval = null;
function onClickHandler(info, tab) {
if (info.menuItemId == "addon") {
if (interval != null) {
clearInterval(interval);
interval = null;
} else {
interval = setInterval(func, 1000);
}
}
};
chrome.contextMenus.onClicked.addListener(onClickHandler);
chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({"title": "Addon", "id": "addon"});
}
1. If previous script.js finished and 1 second after previous
interval call passed, call new script.js
2. If previos script.js finished and 1 second after previous
interval call haven't passed, wait for 1 second and call new script.js
3. If previous script.js haven't finished, wait until it finish
and if 1 second passed, call new script.js
chrome.tabs.executeScript
回调需要同步结果。然而,您的逻辑是异步的。在这种情况下,您必须建立适当的进程间通信。
background.js
chrome.tabs.executeScript(null, {file: 'script.js'});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action === 'done') {
console.log(request.result);
// some code
sendResponse({ action: 'next', arg: 2 });
}
// uncomment this if code is also asynchronous
// return true;
});
// optional
// chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
// chrome.tabs.sendMessage(tabs[0].id, { action: 'next', arg: 1 });
// });
script.js
function func1() {
// some code
var result = 1;
done(result);
}
function func1(2) {
// some code
var result = 2
done(result);
}
function runAction(which) {
switch (which) {
case 1: setTimeout(func1, 500); break;
case 2: setTimeout(func2, 500); break;
}
}
function done(result) {
var msg = { action: 'done', result: result }};
chrome.runtime.sendMessage(msg, function(response) {
if (response.action === 'next') {
runAction(response.arg);
}
});
}
// start
runAction(1);
- 单击按钮以等待单击按钮
- React组件等待所需道具进行渲染
- 选项卡侦听器未被来自后台脚本的消息激活
- 正在等待呈现图表,直到加载数据为止
- 在等待ajax请求时显示微调器并禁用页面
- Javascript在for循环中等待处理请求
- JavaScript循环并等待函数
- WinJS(WP8.1):从后台任务更新辅助磁贴
- JS页面在后台加载时显示动画
- 在等待异步任务时永久循环
- Mozilla没有;t在附加视频src后触发视频后台事件
- 将图像从后台页面传递给内容脚本javascript
- 如何为后台更改程序代码设置cookie
- 在通过child.print()打印之前,我如何等待图像加载到我的新窗口中
- 失败:等待Protractor与页面同步时出错:“”;在窗口上找不到角度”;
- 等待300毫秒,然后使用jQuery向下滑动菜单
- 当绑定到AngularJS中的函数时,会在后台发生什么
- 如何在JavaScript中创建一个等待函数,允许您在后台运行音频等内容
- Chrome扩展:如何使后台等待执行
- 我如何使web浏览器完成加载过程,尽管我正在后台运行等待的AJAX请求