don*_*tos 4 javascript google-chrome google-chrome-extension google-chrome-app
我正在尝试向新创建/更新的选项卡发送消息并在那里接收:
var tabAction = 'create'; // tabAction equals *create* or *update*
chrome.tabs[tabAction]({
url: chrome.extension.getURL('/somepage.htm'),
active: true
}, function(_tab) {
chrome.tabs.sendMessage(_tab.id, {
message: 'some custom message',
arg: 'some arg'
});
});
Run Code Online (Sandbox Code Playgroud)
在此调用之后,其中一个脚本(包含在打开页面的标题中)必须接收此消息并执行进一步操作:
(function(window, document, jQuery) {
"use strict";
chrome.runtime.onMessage.addListener(function(message) {
// Do stuff
});
})(window, document, jQuery);
Run Code Online (Sandbox Code Playgroud)
现在我的问题:
如果tabAction设置为"create",一切正常 - 页面正在加载,主脚本发送消息,扩展调试器显示:"Invoked tabs.sendMessage"和"Notified of runtime.onMessage",页面脚本做了什么它必须.
如果tabAction设置为"update" - 正在重定向页面,主脚本也会发送消息,但消息不会发送到运行时; 调试器只在"Invoked tabs.sendMessage"处停止.
为何这种奇怪的行为?感谢所有进一步的回复.
在调用chrome.tabs.create或chrome.tabs.update调用回调时,无法保证页面已完全加载.
如果在您呼叫时页面未完成加载chrome.tabs.sendMessage,则页面将不会收到该消息(您可能会看到"无法建立连接.接收端不存在."如果您选中chrome.runtime.lastError.message).
解决问题的正确方法是使用chrome.tabs.onUpdated检测选项卡何时完成加载:
chrome.tabs.update({
url: chrome.runtime.getURL('/somepage.htm')
}, function(tab) {
chrome.tabs.onUpdated.addListener(function listener(tabId, changeInfo) {
if (tabId === tab.id && changeInfo.status == 'complete') {
chrome.tabs.onUpdated.removeListener(listener);
// Now the tab is ready!
chrome.tabs.sendMessage(tabId, 'custom message whatever');
}
});
});
Run Code Online (Sandbox Code Playgroud)
chrome.tabs.create由于crbug.com/411225,目前这不起作用.在修复该错误之前,您必须使用以下内容:
var tabAction = 'create'; // Or update.
chrome.tabs[tabAction]({
url: chrome.runtime.getURL('/somepage.htm')
}, function(tab) {
// Called when the tab is ready.
var onready = function() {
onready = function() {}; // Run once.
chrome.tabs.onUpdated.removeListener(listener);
// Now the tab is ready!
chrome.tabs.sendMessage(tab.id, 'custom message whatever');
};
// Detect update
chrome.tabs.onUpdated.addListener(listener);
// Detect create (until crbug.com/411225 is fixed).
chrome.tabs.get(tab.id, function(tab) {
if (tab.status === 'complete') {
onready();
}
});
function listener(tabId, changeInfo) {
if (tabId === tab.id && changeInfo.status == 'complete') {
onready();
}
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3452 次 |
| 最近记录: |