【问题标题】:Chrome Extension - From the DOM to Popup.js message passingChrome 扩展 - 从 DOM 到 Popup.js 消息传递
【发布时间】:2013-05-01 17:05:23
【问题描述】:

我正在尝试让一个简单的 Google Chrome 扩展程序工作,其中消息/变量流经以下每个步骤...

  1. DOM 内容(来自特定的 HTML 标记)
  2. Contentscript.js
  3. Background.js
  4. Popup.js
  5. Popup.html

我已经想出了如何将消息/变量发送到 Background.js 并它在一个方向(Background.js -> Popup.jsBackground.js -> Contentscript.js),但是无法成功通过所有三个 (Contentscript.js -> Background.js -> Popup.js)。这是我演示中的文件。

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"
    }
]

}

我有一种感觉,我知道错误是什么,但是对于 manifest_version: 2 来说,文档严重缺乏,很难破译。一个简单、可重复使用的示例对学习过程非常有帮助,因为我确信这是一个常见问题。

【问题讨论】:

    标签: google-chrome-extension sendmessage


    【解决方案1】:

    好的,更改代码中的一些内容应该可以使其按您的意愿工作。并非我将要进行的所有更改都是必要的,但这正是我可能要做的。

    内容脚本

    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);
    });
    

    【讨论】:

    • 这正是我想要的。非常感谢!
    • 我试过这个。弹出窗口不显示任何内容。我根据我的网站更改了 fromDOM
    • @Venky 用您的代码提出您自己的问题,我将能够更好地帮助您。
    • @BeardFist 非常感谢。几天来我一直在搜寻,试图让它发挥作用,这是唯一适合我的解决方案。
    猜你喜欢
    • 2015-02-13
    • 2016-09-13
    • 2011-03-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多