在chrome.browserAction.onClicked上调用内容脚本函数 [英] Calling Content Script function on chrome.browserAction.onClicked

查看:914
本文介绍了在chrome.browserAction.onClicked上调用内容脚本函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题相当简单,我只想找出最简单的方法来做到这一点。



我的chrome扩展的当前迭代通过一个按钮将一个DIV插入到网页中,当按下按钮时,该按钮将执行一个函数。

我想在不注入DIV的情况下通过在工具栏中按下浏览器按钮时在其中一个内容脚本中执行一个函数来执行此操作。这个最简单的方法是什么?我相信我必须使用后台页面,而我在文档中看到的唯一一件事是在两端注册一些监听事件。如果这是唯一的/最简单的方式,我该如何去做这件事? 是的,联系内容脚本从一个浏览器或页面动作按钮是使用在后台脚本和内容脚本之间来回发送的消息完成的。第一步:告诉后台脚本该做什么browserAction / pageAction按钮点击

  chrome.browserAction.onClicked.addListener(function(tab){
...
});

第二步:在 browserAction.onClicked 事件监听器,然后你可以发送消息到内容脚本(实际上是任何代码监听!):

  chrome.tabs。 sendMessage(tab.id,{< YOURMESSAGEPAYLOAD>}); 

步骤3:在内容脚本内部,为收到的消息添加侦听器

  chrome.runtime.onMessage.addListener(function(request,sender,callback){
//请求包含上面作为Javascript发送的YOURMESSAGEPAYLOAD对象文字
});

您也可以换个角度,通过使用内容脚本将消息发送到后台脚本内容脚本中包含以下内容:

  chrome.runtime.sendMessage({< YOURMESSAGEPAYLOAD>}); 

然后使用 onMessage 侦听器后台脚本与上述相同。


My question is fairly simple and I just want to figure out the easiest way to do this.

The current iteration of my chrome extension injects a DIV into the webpage with a button, which, when pressed, will execute a function.

I want to do this without injecting DIVs, by executing a function within one of my content scripts when the browser button is pressed in the toolbar. What's the simplest way to go about this? I believe I have to use the background page, and the only thing I see in documentation is registering some listening events on both ends. If this is the only/simplest way, how do I go about doing this?

解决方案

Yes, contacting a content script from a browser or page action button is done using messages sent back and forth between the background script and the content script(s)

First step: Tell the background script what to do on browserAction/pageAction button click

chrome.browserAction.onClicked.addListener(function(tab) {
   ...
});

Step 2: Inside the browserAction.onClicked event listener you can then send a message to the content script (in fact to any code listening!):

chrome.tabs.sendMessage(tab.id, {<YOURMESSAGEPAYLOAD>});

Step 3: Inside the content script, you add a listener for incoming messages

chrome.runtime.onMessage.addListener(function(request, sender, callback) {
   // request contains the YOURMESSAGEPAYLOAD sent above as a Javascript object literal
});

You can also go the other way round and send messages from the content script to the background script by using the following inside the content script

chrome.runtime.sendMessage({<YOURMESSAGEPAYLOAD>});

and then use the onMessage listener inside the background script the same way as mentioned above.

这篇关于在chrome.browserAction.onClicked上调用内容脚本函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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