Chrome Extension - From the DOM to Popup.js messag

2019-01-17 08:23发布

问题:

I'm trying to get a simple Google Chrome extension working where a message/variable flows through each of the following steps ...

  1. DOM content (from specific HTML tag)
  2. Contentscript.js
  3. Background.js
  4. Popup.js
  5. Popup.html

I've figured out how to send a message/variable to Background.js and from it in one direction (Background.js -> Popup.js or Background.js -> Contentscript.js), but can't get it through all three successfully (Contentscript.js -> Background.js -> Popup.js). Here are the files in my demo.

Dom

<h1 class="name">Joe Blow</h1>

Content.js

fromDOM = $('h1.name').text();

chrome.runtime.sendMessage({contentscript: "from: contentscript.js", title: fromDOM}, function(b) {
    console.log('on: contentscript.js === ' + b.background);
});

Background.js

chrome.tabs.getSelected(null, function(tab) {
    chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {

        sendResponse({background: "from: background.js"});
        console.log('on: background.js === ' + msg.title);

    });
});

Popup.js

chrome.extension.sendMessage({pop: "from: popup.js"}, function(b){
    console.log('on: popup.js === ' + b.background);

    $('.output').text(b.background);
});

Popup.html

<html>
<head>
  <script src="jquery.js"></script>
  <script src="popup.js"></script>
</head>
<body>

<p class="output"></p>

</body>
</html>

Manifest.json

{   
"name": "Hello World",   
"version": "1.0",
"manifest_version": 2,
"description": "My first Chrome extension.",
"background" : {
    "scripts": ["background.js"]
},
"permissions": [
    "tabs"
],
"browser_action": {     
    "default_icon": "icon.png",
    "default_popup": "popup.html"   
},
"content_scripts": [
    {
      "matches": ["http://*/*"],
      "js": ["jquery.js","contentscript.js"],
      "run_at": "document_end"
    }
]

}

I have a feeling I know what the trip-up is, but the documentation is severely lacking for manifest_version: 2 that its tough to decipher. A simple, reusable example would be very helpful in the learning process, as I'm sure this is a common issue.

回答1:

Alright, changing a few things in your code should make it work like you want. Not all of the changes I am going to make are necessary, but this is just how I might do it.

Content Script

var fromDOM = $('h1.name').text();
chrome.runtime.sendMessage({method:'setTitle',title:fromDOM});

Background

var title;
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
  if(message.method == 'setTitle')
    title = message.title;
  else if(message.method == 'getTitle')
    sendResponse(title);
});

Popup.js

chrome.runtime.sendMessage({method:'getTitle'}, function(response){
  $('.output').text(response);
});