本文介绍了从Chrome扩展程序的内容脚本接收消息到按钮的Click事件上的后台js文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的扩展打开了一个包含按钮的html页面(dashboard.html)。点击甚至按钮我想接收内容脚本发送的消息。不知何故,我无法做到这一点。代码如下:

manifest.json

 <$ c 
manifest_version:2,
name:My Ext,
description:XXX,
version:1.0 ,
权限:[
标签
],
content_scripts:[{
matches:[http://example.com / $],
js:[jquery.js,script.js]
}],
background:{
scripts:[ jquery.js,background.js]
},
browser_action:{
default_title:XX
}
}

dashboard.html

 <!DOCTYPE HTML PUBLIC -  // W3C // DTD HTML 4.01 Transitional // EN> 
< html>
< head>
< title>< / title>
< meta http-equiv =Content-Typecontent =text / html; charset = UTF-8>
< script src =jquery.js>< / script>
< script src =background.js>< / script>
< / head>
< body>
< form>
< textarea id =search>< / textarea>
< input id =buttontype =buttonvalue =Search/>
< / form>
< / body>
< / html>

Script.js

  chrome.runtime.sendMessage({greeting:hello},function(response){
alert(response.farewell);
});

background.js

  var queryStr ='?tabId ='; 
var loaderURL = chrome.extension.getURL('dashboard.html')+ queryStr;
$(document).ready(function()
{
chrome.browserAction.onClicked.addListener(function(tab){
chrome.tabs.create({url:loaderURL + tab.id});
});
if(location.search&&(location.search.indexOf(queryStr)=== 0))
{
)var tabID = parseInt(location.search.substring(queryStr.length));
alert(tabID);
$('#button')。click(function()
{
/ ********下面的COde没有产生任何结果** /
chrome.runtime.onMessage.addListener(
function(request,sender,sendResponse){
从内容脚本中提取(sender.tab?
:+ sender.tab.url:
from the extension);
alert(request.greeting);
if(request.greeting ==hello)
sendResponse({farewell:goodbye});
});


});

}
});


解决方案

我不明白为什么您需要发送消息从内容脚本中,因为您可以使用 sendResponse 来传回任何必要的数据,但是...



$ b manifest.json

  {
manifest_version:2,
name:Test Extension,
version:0.0,

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

content_scripts:[{
matches:[*:// * / *],
js:[jquery.min.js,content.js],
}],

browser_action:{
default_title:测试扩展名
//default_icon:{
//19:img / icon19.png ,
//38:img / icon38.png
//},
},

}






background.js

  var queryStr ='?tabId ='; 
var loaderURL = chrome.extension.getURL('dashboard.html')+ queryStr;
chrome.browserAction.onClicked.addListener(function(tab){
chrome.tabs.create({url:loaderURL + tab.id});
});






content.js

  chrome.runtime.onMessage.addListener(function(msg,sender,sendResponse){ 
alert('Message from a view:\\\
'
+ JSON.stringify(msg));

if(msg.method ==='getHTML'){
sendResponse({data:'欢迎来自内容脚本'));
chrome.runtime.sendMessage({
body:'在这里,给你发送另一条消息!'
});
}
});






dashboard.html

 <!DOCTYPE html> 
< html>
< head>
< title> Dashboard< / title>
< script src =jquery.min.js>< / script>
< script src =dashboard.js>< / script>
< / head>
< body>
< form>
< textarea id =search>< / textarea>< br />
< input type =buttonid =buttonvalue =Search/>
< / form>
< / body>
< / html>






dashboard.js

  var queryStr ='?tabId ='; 

chrome.runtime.onMessage.addListener(function(msg,sender){
alert('Message from:Tab'+ sender.tab.id +'(using`sendMessage`) \\ n'
+ JSON.stringify(msg));
});

$(document).ready(function(){
if(location.search&&(location.search.indexOf(queryStr)=== 0)){
var tabID = parseInt(location.search.substring(queryStr.length));
$('#button')。click(function(){
chrome.tabs.sendMessage(tabID,{
方法:'getHTML',
param:'myParam'
},函数(响应){
if(chrome.runtime.lastError){
alert(' ERROR:'+ chrome.runtime.lastError.message);
} else {
alert('Message from:Tab'+ tabID
+'(using`sendResponse`)\\\
'
+ response.data);
}
});
});
}
});






还有一件事:




  • 您不需要标签权限(至少对于目前显示的功能而言)。这是一个强大的权限,所以不要轻易使用(出于安全原因和不吓跑用户)。


My extension opens up an html page(dashboard.html) which contains a button. On click even of the button I want to receive message being sent by content script. Somehow I am not being able to do that. Code is given below

manifest.json

{
    "manifest_version": 2,
    "name" : "My Ext",
    "description" : "XXX",
    "version" : "1.0",
    "permissions": [
        "tabs"
  ],
    "content_scripts" : [{
        "matches" : ["http://example.com/"],
        "js" : ["jquery.js","script.js"]
    }],
"background":{
  "scripts": ["jquery.js","background.js"]
},
    "browser_action": {
        "default_title": "XX"
      }
}

dashboard.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script src="jquery.js"></script>
    <script src="background.js"></script>
  </head>
  <body>
      <form>
      <textarea id="search"></textarea>
      <input id="button" type="button" value="Search" />
      </form>
  </body>
</html>

Script.js

    chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
  alert(response.farewell);
});

background.js

    var queryStr = '?tabId=';
var loaderURL = chrome.extension.getURL('dashboard.html') + queryStr;
$(document).ready(function ()
{
    chrome.browserAction.onClicked.addListener(function (tab) {
        chrome.tabs.create({ url: loaderURL + tab.id });
    });
    if (location.search && (location.search.indexOf(queryStr) === 0))
    {
        var tabID = parseInt(location.search.substring(queryStr.length));
        alert(tabID);
        $('#button').click(function ()
        {
          /********following COde is not producing any result **/
            chrome.runtime.onMessage.addListener(
              function(request, sender, sendResponse) {
                alert(sender.tab ?
                            "from a content script:" + sender.tab.url :
                            "from the extension");
                alert(request.greeting);
                if (request.greeting == "hello")
                  sendResponse({farewell: "goodbye"});
              });


        });

    }
});
解决方案

I don't understand why you need to send message from content script, since you can use sendResponse to pass back any necessary data, but...


In manifest.json:

{
    "manifest_version": 2,
    "name":    "Test Extension",
    "version": "0.0",

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

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

    "browser_action": {
        "default_title": "Test Extension"
//        "default_icon": {
//            "19": "img/icon19.png",
//            "38": "img/icon38.png"
//        },
    },

}


In background.js:

var queryStr = '?tabId=';
var loaderURL = chrome.extension.getURL('dashboard.html') + queryStr;
chrome.browserAction.onClicked.addListener(function (tab) {
    chrome.tabs.create({ url: loaderURL + tab.id });
});


In content.js:

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    alert('Message from a view:\n'
          + JSON.stringify(msg));

    if (msg.method === 'getHTML') {
        sendResponse({ data: 'Welcome from Content Script' });
        chrome.runtime.sendMessage({
            body: 'Here I am, sending you another message !'
        });
    }
});


In dashboard.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Dashboard</title>
        <script src="jquery.min.js"></script>
        <script src="dashboard.js"></script>
    </head>
    <body>
        <form>
            <textarea id="search"></textarea><br />
            <input type="button" id="button" value="Search" />
        </form>
    </body>
</html>


In dashboard.js:

var queryStr = '?tabId=';

chrome.runtime.onMessage.addListener(function(msg, sender) {
    alert('Message from: Tab ' + sender.tab.id + ' (using `sendMessage`)\n'
          + JSON.stringify(msg));
});

$(document).ready(function () {
    if (location.search && (location.search.indexOf(queryStr) === 0)) {
        var tabID = parseInt(location.search.substring(queryStr.length));
        $('#button').click(function () {
            chrome.tabs.sendMessage(tabID, {
                method: 'getHTML',
                param:  'myParam'
            }, function (response) {
                if (chrome.runtime.lastError) {
                    alert('ERROR: ' + chrome.runtime.lastError.message);
                } else {
                    alert('Message from: Tab ' + tabID
                          + ' (using `sendResponse`)\n'
                          + response.data);
                }
            });
        });
    }
});


One more thing:

  • You don't need the tabs permission (at least for the presently shown functionality). It is a powerful permission, so don't use light-heartedly (for securty reasons and for not scaring users).

这篇关于从Chrome扩展程序的内容脚本接收消息到按钮的Click事件上的后台js文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 06:44