Chrome.extension.sendMessage within chrome.tabs.create
Chrome.extension.sendMessage within chrome.tabs.create
我需要创建一个 chrome 扩展程序来捕获当前可见的选项卡并在新选项卡中打开它。我使用以下代码:
发送.js
function openNextPage(imagesrc) {
chrome.tabs.create({url: "newScreen.html"},function(tab){
chrome.runtime.sendMessage({someParam: imagesrc},function(response){console.log(response);});
}
);
}
在newScreen中.html我包含了receive.js如下所示:
window.addEventListener("load",function(){
console.log('contents Loaded');
chrome.runtime.onMessage.addListener(function(request,sender,response) {
console.log(request.someParam);
});
});
问题是,一旦创建了新选项卡(第一个新屏幕.html),我可以看到内容加载消息,但看不到图像rc。也许是因为onMessage.addEventListener稍后执行(在sendMessage之后)。
但是,如果我再次单击我的扩展程序并打开第二个新屏幕.html,上一个新屏幕.html会收到消息并打印它。如果我打开第三个选项卡,第一个和第二个选项卡将再次收到消息。问题是sendMessage甚至在添加onMessageListener之前就执行了。我使用超时发送消息,但徒劳无功。帮帮我!
你是说
也许是因为
onMessage.addEventListener
稍后执行(sendMessage
之后)。
是的,这是真的:您正在使用window.onload
侦听器等待窗口加载,但消息是在窗口完全加载之前发送的。您应该将chrome.runtime.onMessage
侦听器从window.onload
侦听器中移出,如下所示:
chrome.runtime.onMessage.addListener(function(request,sender,response) {
console.log(request.someParam);
});
window.addEventListener("load",function(){
console.log('contents Loaded');
});
如果需要,可以将请求存储在某个全局变量中,以便可以在 window.onload
事件处理程序中使用它,并确保在加载窗口时完成所有工作,如下所示:
var MY_PARAMETER;
chrome.runtime.onMessage.addListener(function(request,sender,response) {
MY_PARAMETER = request.someParam;
});
window.addEventListener("load",function(){
// Now you are sure that the window is loaded
// and you can use the MY_PARAMETER variable
console.log("Contents loaded, MY_PARAMETER =", MY_PARAMETER);
});
显然,您需要将此receive.js
脚本放在标记的顶部,在文档的<head>
内,以确保尽快添加侦听器:
<html>
<head>
...
<script src="/path/to/request.js"></script>
...
</head>
...
</html>
相关文章:
- 在chrome.tabs.onCreated之后加载HTML页面
- chrome.tabs.update() 重定向到 'chrome-extension://invalid/'
- Chrome扩展,Chrome.tabs.query的结果未定义
- AngularJS Navigation (li ng-repeat, create header li), DOM
- 使用Object.create()的角度服务继承
- 在使用object.create创建的对象中使用super
- primefaces jquery ui tabs
- chrome.tabs.create的回调不会在弹出窗口中触发
- Backbone - Collection.add() / Collection.create() 之间的区别
- 如何在ajax重定向中传递create-formbuilder
- ColdFusion.Window.create不刷新弹出窗口
- 禁用facebook在like按钮启动edge.create事件
- 正在使用object.create()创建XMLHttpRequest对象
- Stripe API:没有ID为X的令牌(Stripe.cocharges.create)
- Object.create()只读名称属性
- 如何将值传递到由chrome.tabs.create打开的新选项卡
- Chrome.extension.sendMessage within chrome.tabs.create
- chrome.tabs.create/executeScript >属于页面的调用函数
- 谷歌浏览器扩展:for loop来分配chrome.tabs.create函数
- chrome.tabs.create - 从未调用过回调函数