Chrome扩展程序 - 从后台生成报告但在弹出窗口中显示?

时间:2017-07-10 08:15:25

标签: javascript google-chrome google-chrome-extension frontend

我正在编写Chrome扩展程序,所有分析都发生在我的background.js中。假设结果来自此脚本,格式为HTML表格,那么如何在弹出页面中显示它,即用户点击扩展图标后的页面?

非常感谢!

这是我的manifest.js

{
  "manifest_version": 2,

  "name": "myExtension",
  "description": "...",
  "version": "1.0",

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

  "browser_action": {
    "default_icon": "lightning.png",
    "default_title": "Click here!",
    "default_popup": "intro.html"
    },

  "permissions": [
    "background",
    "activeTab",
    "tabs",
    "bookmarks",
    "webRequestBlocking",
    "webRequest",
    "<all_urls>",
    "debugger"
    ]
}

1 个答案:

答案 0 :(得分:1)

这个想法是将消息监听器保留在后台脚本中,因此每次弹出窗口运行时都会要求报告。

这就是代码:

<强>的manifest.json

{
    "name": "test",
    "version": "0.0.1",
    "manifest_version": 2,
    "description": "Test",

    "background": {
        "scripts": [
            "background.js"
        ]
    },
    "permissions": [],

    "browser_action": {
        "default_popup": "popup.html"
    }
}

<强> popup.html

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>

<div id="report"></div>


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

<强> popup.js

var reportContainer = document.querySelector('#report');

chrome.runtime.sendMessage({action: 'report'}, function (response) {
    reportContainer.innerHTML = response;
});

<强> background.js

var report = '<h1>hello from background</h1>';

chrome.runtime.onMessage.addListener(
    function(data, sender, sendResponse) {
        if(data.action === 'report') {
            sendResponse(report);   
        }
    }
);