最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - "Communicate" the contents js and background js files in extension - Stack Overflow

programmeradmin3浏览0评论

I am writing an extension and I encountered a problem: I can not send data from the extension menu to content.js. In the extension menu I have a couple of intuitions, after filling in and clicking on the button, I write down their values and I want to send them to content.js where this data will be used for implementation inhtml But for some reason, the data is not sent.

document.getElementById('btn').onclick = function() {
  var first = document.getElementById('first').value;
  var second = document.getElementById('second').value;
  //send in content
  chrome.extension.sendMessage('hello');
}
<head>
  <script type="text/javascript" src="content.js"></script>
  <script type="text/javascript" src="background.js"></script>
</head>
<input type="text" id="first">
<input type="text" id="second">
<input type="button" id="btn" value="send">

I am writing an extension and I encountered a problem: I can not send data from the extension menu to content.js. In the extension menu I have a couple of intuitions, after filling in and clicking on the button, I write down their values and I want to send them to content.js where this data will be used for implementation inhtml But for some reason, the data is not sent.

document.getElementById('btn').onclick = function() {
  var first = document.getElementById('first').value;
  var second = document.getElementById('second').value;
  //send in content
  chrome.extension.sendMessage('hello');
}
<head>
  <script type="text/javascript" src="content.js"></script>
  <script type="text/javascript" src="background.js"></script>
</head>
<input type="text" id="first">
<input type="text" id="second">
<input type="button" id="btn" value="send">

Here is the manifest.json (maybe there's something wrong)

{

 "manifest_version": 2,
 "version": "1.3",
 "description": "name",
 "browser_action":{
    "default_popup": "content/popup.html"
 },
     "background": {
     "persistent": false,
         "scripts": ["content/background.js"]
        },
      "content_scripts": [
          {
             "matches": [ "https://google./*" ],
             "js": ["content/content.js"],
             "css": ["content/qq.css"],
             "run_at": "document_end"
         }
     ]
 }

content.js: get data from background

chrome.extension.onMessage.addListener(function(request){
    if(request=='hello'){
        console.log('1. Принято: ', request);
    }
});

As I can see everything, background.js is the file that is responsible forjs in the extension menu. content.js is the file that is responsible for making changes to the DOM on the sites.

Share Improve this question edited Dec 24, 2017 at 13:15 Tick-Tack asked Dec 23, 2017 at 19:57 Tick-TackTick-Tack 2132 silver badges22 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

Your files' structure is unclear: what is the content of popup.html? why do you load both content.js and background.js in the same page?

Here is an example that does what I think you try to acplish.

It works like this:

The popup screen will display the inputs for the user to fill. When the button is pressed, the value of the inputs is sent to the background script which, in turn, sends them to the content script. The content script then uses those values in the way you want: for instance, to fill an input in the host webpage.

manifest.json

{

 "manifest_version": 2,
 "version": "1.3",
 "description": "name",
 "browser_action":{
    "default_popup": "content/popup.html"
 },
 "background": {
     "persistent": true,
     "scripts": ["content/background.js"]
 },
 "content_scripts": [
     {
         "matches": [ "https://google./*" ],
         "js": ["content/content.js"],
         "css": ["content/qq.css"],
         "run_at": "document_end"
     }
 ]
}

background.js

var contentTabId;

chrome.runtime.onMessage.addListener(function(msg,sender) {
  if (msg.from == "content") {  //get content scripts tab id
    contentTabId = sender.tab.id;
  }
  if (msg.from == "popup" && contentTabId) {  //got message from popup
    chrome.tabs.sendMessage(contentTabId, {  //send it to content script
      from: "background",
      first: msg.first,
      second: msg.second
    });
  }
});

content.js

chrome.runtime.sendMessage({from:"content"}); //first, tell the background page that this is the tab that wants to receive the messages.

chrome.runtime.onMessage.addListener(function(msg) {
  if (msg.from == "background") {
    var first = msg.first;
    var second = msg.second;
    //here you use the values as you wish, for example:
    //document.getElementById("anInput").value = first;
  }
});

popup.html

<html>
  <body>
    <input type="text" id="first">
    <input type="text" id="second">
    <button id="send">Send</button>
    <script src="popup.js"></script>
  </body>
</html>

popup.js (this file must be located in the same directory as popup.html)

document.getElementById("send").onclick = function() {
  chrome.runtime.sendMessage({  //send a message to the background script
    from: "popup",
    first: document.getElementById("first").value,
    second: document.getElementById("second").value
  });
}

I hope that helps.

I think you are looking for the runtime property of the chrome / browser object.

This would make your send message mand chrome.runtime.sendMessage without the use of the extension property.

Likewise the on message event would be chrome.runtime.onMessage.

I'm pulling this info from the following documentation: https://developer.chrome./apps/messaging

content.js should not be included into popup.html. content.js is run whenever a site matches the pattern in your manifest.json. Right now, whenever someone visits google. with your extension installed, the content.js script is run in the background of google..

background.js also shouldn't be loaded into the popup. It's a script that's always run in the background of the browser, it's not something that should get loaded by anything. It's where you add stuff like code to change the omnibox behavior.

You should create a new popup.js script that gets included by popup.html, and it should only handle things like onload and onclick events for the actual popup window.

The various files you mention, content.js, background.js and the file you should create popup.js all have different jobs and should not municate between each other. There's neither a need nor a possibility for it. If you want to e.g. get the value of what's inside some other site put it in content.js, which is run on each site that matches your pattern, and do all the handling in there.

background.js = code that sets up your extension inside the browser, stuff like changing the omnibox behavior.

content.js = code that runs on each website that matches a certain pattern.

popup.js = code that runs when the user opens the popup window of your extension.

So don't have them municate, they aren't supposed to, they fill entirely different functions.

There's no reason why you should need to municate between them either, please explain a scenario where you'd need this and I'll explain why you don't need it. :)

To municate with content.js, you need to use chrome.tabs.sendMessage instead of chrome.extension.sendMessage, because to municate with the content.js you need to provide the tabId, which is passed as an argument in the former listed API.

发布评论

评论列表(0)

  1. 暂无评论