【发布时间】:2016-07-10 21:22:41
【问题描述】:
我正在开发一个 chrome 扩展,其中我的 popup.js 从当前页面上的内容脚本接收消息并创建一个数组。然后按下按钮,popup.js 会创建一个新选项卡(其中运行内容脚本)并向该内容脚本发送包含数组的消息。
我的 popup.js:
//this message is sent from a different content script (for current page), not shown here
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action === "getSource") {
var arr = JSON.parse(request.source);
//create new tab
chrome.tabs.create({url: "newtab.html"}, function(tab){
//send message to new tab
chrome.tabs.sendMessage(tab.id{
action: "getDataArray",
source: JSON.stringify(arr)
});
}
});
newtab-contentscript.js:
$(document).ready( function() {
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action === "getDataArray") {
$("#result").html(JSON.parse(request.source));
}
});
newtab.html:
<script src="newtab-contentscript.js"></script>
问题:newtab-contentscript.js 似乎从未收到消息。
我创建标签或发送消息的方式有什么错误吗?您对如何解决此问题有任何建议吗?
【问题讨论】:
-
我猜(还没有深入挖掘扩展平台的源代码)可能
$(document).ready来不及接收来自chrome.tabs.sendMessage的消息。但是,我相信将消息逻辑移动到后台(事件)页面并启动从newtab-contentscript.js传递的消息是一个好方法,这样您可以控制何时开始发送消息。 -
是的,这基本上是一个答案。时间问题可以通过比较回调内部和新标签内容脚本第一行上
console.log的时间戳来确认。 -
感谢您的意见! @HibaraAi 你能详细说明你的建议吗?您是否建议我从后台页面创建一个新选项卡,而不是将其发送到 popup.js?我尝试了这个,但是后台脚本无法使用诸如创建选项卡之类的 chrome 功能。
-
我还尝试将 newtab-contentscript.js 中的监听器移到 $(document).ready 之外,但似乎没有什么不同。
标签: google-chrome google-chrome-extension