11

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.

4

1 回答 1

22

好吧,在你的代码中改变一些东西应该让它像你想要的那样工作。并非我将要进行的所有更改都是必要的,但这正是我可能会这样做的方式。

内容脚本

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

背景

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);
});
于 2013-05-01T19:56:03.887 回答