0

I'm writing up a chrome extension, with all analysis happening in my background.js. Say the result comes out from this script, in the format of a HTML table, then how can I show it in the pop up page, which is the page after the user clicks on the extension icon?

Many thanks!

This is my 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"
    ]
}
lsheng
  • 3,539
  • 10
  • 33
  • 43
  • Use message passing and send to content script – Madhan Jul 10 '17 at 09:39
  • You have to communicate it to the popup page. See: [Communicate between scripts in the background context (background script, browser action, page action, options page, etc.)](https://stackoverflow.com/a/41420772) – Makyen Jul 11 '17 at 21:14

1 Answers1

1

The idea is to keep message listener in background script, so each time popup is running it asks for a report.

That is the code:

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);   
        }
    }
);
Denis L
  • 3,209
  • 1
  • 25
  • 37
  • I recently learned to use "var background_data = chrome.extension.getBackgroundPage().report" for example, just wondering what is the difference while I do "sendResponse( report)"? – lsheng Jul 12 '17 at 09:06
  • 1
    Using `getBackgroundPage` also a solution for this task, but using messaging become an advantage when you extension starts to increase – Denis L Jul 12 '17 at 09:12
  • Got it, pretty clear, thanks! – lsheng Jul 12 '17 at 09:57