本文介绍了JavaScript Chrome扩展程序-在创建新选项卡后从弹出窗口发送到内容后发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我所涉及的popup.js中,我想创建一个新选项卡并发送一条消息. content.js必须侦听消息并回答,但不起作用!我尝试了其他问题中找到的很多解决方案,但没有成功这是我的文件:

in a popup.js of my extention, i want to create a new tab and send a message. content.js has to listen the message and answer but it doesn't work! i tried a lot of solution found in other question but without successhere my files:

{
  //Manifest.json
  "name": "Stampa cedolini",
  "description": "stampa automatica dei cedolini",
  "version": "1.0",
  "permissions": [
      "tabs", "http://*/*", "https://*/*"
   ],

  "content_scripts":  [{
     "matches": [ "http://*/*", "https://*/*"],
     "js": [ "jquery-2.1.3.min.js" ,"content.js"]
   }],

  "browser_action": {
       "default_title": "Scegli la persona.",
       "default_icon": "icon.png",
       "default_popup": "popup.html"
   },
  "manifest_version": 2
}

popup.js:

function click(e) {
    var link1 = "http://www.example1.it";

var link2 = "http://www.example2.com";
if (e.target.id === "pippo") {
    chrome.tabs.create({ url: link1 }, function(tab) {
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            // your code ...
            chrome.tabs.executeScript({code:"console.log('"+tabs[0].id+"')"});
            //chrome.tabs.executeScript({code:"alert("+tabs[0].id+");"});
            chrome.tabs.sendMessage(tabs[0].id, {persona: "pippo"});
        });
    });
} else {
    chrome.tabs.create({ url: link2 }); 
}
 //window.close();
}

document.addEventListener('DOMContentLoaded', function () {
   var divs = document.querySelectorAll('div');
   for (var i = 0; i < divs.length; i++) {
   divs[i].addEventListener('click', click);
}
});

和content.js:

and content.js:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
     alert("from a content script:" + sender.tab.url);
     if (request.persona == "pippo") {
         sendResponse({risp: "ricevuto"});
     }
});

tabs.create回调中的console.log(tab.id)已打印,但似乎无法发送消息有人能帮我吗??谢谢

the console.log(tab.id) in tabs.create callback is printed but seems that fails the send message Can someone help me??thanks

推荐答案

默认情况下,它在document_idle处加载的内容脚本.

Your content script it loaded, by default, at document_idle.

这意味着到您发送邮件时,它还不存在,并且没有人收听您的邮件.

Which means that by the time you send the message, it's not there yet, and nothing listens to your message.

如果要通过代码创建选项卡,则最好以编程方式注入内容脚本,而不要依赖清单注入,并使用回调确保已完成执行.

If you are creating a tab from code, it's best to programmatically inject your content script and not rely on the manifest injection, and use the callback to ensure it's done executing.

chrome.tabs.create({ url: link1 }, function(tab) {
  // Why do you query, when tab is already given?
  chrome.tabs.executeScript(tab.id, {file:"jquery-2.1.3.min.js"}, function() {
    // This executes only after jQuery has been injected and executed
    chrome.tabs.executeScript(tab.id, {file:"jcontent.js"}, function() {
      // This executes only after your content script executes
      chrome.tabs.sendMessage(tab.id, {persona: "pippo"});
    });
  });
});

也就是说,您可能要考虑在后台脚本而不是在弹出窗口中调用此代码.一旦弹出窗口失去焦点,您的弹出页面就会开始卸载,并且您的代码可能无法完成执行.最好将请求创建选项卡的消息发送给后台脚本.

That said, you may want to consider calling this code in the background script and not in the popup. As soon as popup loses focus, your popup page starts to unload and your code may not finish executing. It's better if you message the background script with a request to create the tab.

这篇关于JavaScript Chrome扩展程序-在创建新选项卡后从弹出窗口发送到内容后发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 18:32