消息从Chrome扩展传递示例 [英] Message Passing Example From Chrome Extensions

查看:146
本文介绍了消息从Chrome扩展传递示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Google教程中的示例,并发现很难将简单的消息传递给内容脚本。



您能否提供一些关于如何传递简单消息并在控制台日志或警报中查看它的建议?



manifest.json

  {
manifest_version :2,

name:msg-test,
description:message test,
version:1.0,

browser_action:{
default_icon:icon.png,
default_popup:popup.html
},

background:{
scripts:[background.js],
persistent:true
},

content_scripts:[ {
匹配:[http:// * / *,http://www.site.com/*],
js:[content.js] ,
run_at:document_end
}],

权限:[
标签,
http:// * / *
]
}

background.js

  chrome.runtime.onConnect.addListener(function(port){
port .postMessage({问候: 你好});
});

content.js

  var port = chrome.runtime.connect({name:content}); 
port.onMessage.addListener(function(message,sender){
if(message.greeting ===hello){
alert(message.greeting);
}
});

popup.js

  window.onload = function(){

document.getElementById('btn2')。onclick = function(){
alert 按钮2被点击);
};

document.getElementById('btn1')。onclick = function(){
alert(button 1 was clicked);
};

$ b}

*注意:在本例中,内容脚本会在页面匹配manifest.json时触发,并且警报框会显示。 解决方案

首先,我不会传递消息弹出窗口和内容脚本之间。我会在您的后台页面和您的内容脚本之间传递消息。您的弹出式页面只能用于显示某些用户界面与您的应用进行交互。



据说,我会告诉你在你的背景和你的内容脚本之间传递消息的方式。



<在您的内容脚本中:

  //此行打开与您的背景页面的长期连接。 
var port = chrome.runtime.connect({name:mycontentscript});
port.onMessage.addListener(function(message,sender){
if(message.greeting ===hello){
alert(message.greeting);
}
});

在您的背景页面(可能是您的弹出窗口?但我不推荐它)



pre $ chrome.runtime.onConnect.addListener(function(port){
port.postMessage({greeting:hello});
});

以下是将要发生的事件序列:


  1. 您的应用程序会将您的内容脚本插入到页面中
  2. 您的内容脚本将打开一个端口与后台脚本进行通信。
  3. li>
  4. 您的后台脚本会收到通知,表示端口已打开,允许其发送消息或附加消息侦听器。

在后台脚本或内容脚本中,您可以使用 port.onMessage.addListener()来监听消息。只要端口在范围内。使用端口更容易掌握,并允许进行简单的双向通信!



编辑:



如果你想要通过弹出脚本将消息传递到您的背景页面,请使用完全相同的方法:

  var port = chrome.runtime .connect({name:popup-port}); 
port.postMessage({status:poppedup});

编辑2:



用户转到新页面,执行此操作:

  function navigateToPage(url){
chrome.tabs.query({ url:url},函数(tabs){
var tab = tabs [0];
return tab?chrome.tabs.update(tab.id,{active:true}):chrome.tabs。 create({url:url});
});
}
});

这个函数的作用是检查是否有一个带有你想要的url的标签去,如果有的话,切换到它,否则,创建一个与该网址的标签,并导航到它。

I'm using the example from the Google tutorial and finding it difficult to pass a simple message to the content script from the popup.

Can you provide some suggestions on how to pass a simple message and view it either in the console log or alert?

manifest.json

{
  "manifest_version": 2,

  "name": "msg-test",
  "description": "message test",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },

  "background": {
    "scripts": ["background.js"],
    "persistent": true
  },

  "content_scripts": [{
     "matches": ["http://*/*","http://www.site.com/*"],
     "js": ["content.js"],
     "run_at": "document_end"
  }],  

  "permissions": [
    "tabs",
    "http://*/*"
  ]  
}

background.js

chrome.runtime.onConnect.addListener(function(port){
  port.postMessage({greeting:"hello"});
});

content.js

var port = chrome.runtime.connect({name:"content"});
port.onMessage.addListener(function(message,sender){
  if(message.greeting === "hello"){
    alert(message.greeting);
  }
});

popup.js

window.onload = function() {

    document.getElementById('btn2').onclick = function() {
       alert("button 2 was clicked");
     }; 

    document.getElementById('btn1').onclick = function() {
        alert("button 1 was clicked");
     }; 


}

*Note: In this example the content script will fire when the page matches manifest.json and the alert box will show.

解决方案

First, I wouldn't message pass between your popup and your content script. I would message pass between your Background page and your content scripts. Your popup page should only be used to show some ui to interact with your app.

With that being said, I will show you the way to pass messages between your background and your content script.

In your content script:

//This line opens up a long-lived connection to your background page.
var port = chrome.runtime.connect({name:"mycontentscript"});
port.onMessage.addListener(function(message,sender){
  if(message.greeting === "hello"){
    alert(message.greeting);
  }
});

In your background page(possibly your popup? but I don't recommend it)

chrome.runtime.onConnect.addListener(function(port){
  port.postMessage({greeting:"hello"});
});

Here is the sequence of events that will take place:

  1. Your application will inject your content script into the page
  2. Your content script will open up a port to communicate with the background script.
  3. Your background script will be notified that a port was open, allowing it to send a message to it, or attach a message listener to it.

In the background script or the content script, you can listen for messages by using port.onMessage.addListener(). provided that port is in scope. Using ports is much easier to grasp and allows for simple, two way communication!

Edit:

If you would like to pass messages to your background page from your popup script, use the exact same method:

var port   =   chrome.runtime.connect({name: "popup-port"});
port.postMessage({status:"poppedup"});

Edit 2:

To navigate your user to a new page, do this:

function navigateToPage(url){
    chrome.tabs.query({url: url}, function(tabs) {
        var tab = tabs[0];
        return tab ? chrome.tabs.update(tab.id, {active:true}) : chrome.tabs.create({url: url});
    });
}
});

What this function does is, it checks to see if there is a tab with the url you want to go to, if there is, switch to it, else, create a tab with that url and navigate to it.

这篇关于消息从Chrome扩展传递示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆