【问题标题】:Chrome extension create new tab and send message from popup.js to content script of new tabChrome 扩展创建新标签并将消息从 popup.js 发送到新标签的内容脚本
【发布时间】: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


【解决方案1】:

正如我们在 cmets 中讨论的那样,我想$(document).ready 可能来不及接收来自chrome.tabs.sendMessage 的消息,您可以通过比较回调内部和新标签第一行上console.log 的时间戳来测试它内容脚本,正如@wOxxOm 提到的那样。

我只是建议将消息​​逻辑移动到后台(事件)页面并启动从newtab-contentscript.js 传递的消息,您可以在其中控制何时开始发送消息。

示例代码

background.js

let source = null;

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    // sent from another content script, intended for saving source
    if(request.action === 'putSource') {
        source = request.source;
        chrome.tabs.create({ url: 'newtab.html' });
    }
    // sent from newtab-contentscript, to get the source
    if(request.action === 'getSource') {
        sendResponse({ source: source });
    }
});

newtab-contentscript.js

chrome.runtime.sendMessage({action: 'getSource'}, function(response) {
    $('#result').html(response.source);
});

【讨论】:

  • 这让我很开心,感谢您发布解决方案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-04
  • 1970-01-01
  • 2011-11-15
  • 2017-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多