Here you can see, content.js sent a message including the selected text. So how we get the message? To achieve this, we need something called background page, which is running in the background. It’s usually called event.js

event.js

1

2

3

4

5

6

7

8

9

10

// This function is called onload in the popup code

functiongetPageDetails(callback) {

// Inject the content script into the current page

chrome.tabs.executeScript(null, { file: 'content.js' });

// Perform the callback when a message is received from the content script

chrome.runtime.onMessage.addListener(function(message) {

// Call the callback function

callback(message);

});

};

event.js is not always running, but it will wake up when another view in the extension (for example, a popup) calls runtime.getBackgroundPage., just like the code in popup.js

popup.js

1

2

3

4

5

6

7

8

9

10

11

12

13

functiononPageDetailsReceived(details) {

document.getElementById('output').innerText = details.summary;

}

// When the popup HTML has loaded

window.addEventListener('load', function(evt) {

// Get the event page

chrome.runtime.getBackgroundPage(function(eventPage) {

// Call the getPageInfo function in the event page, passing in

// our onPageDetailsReceived function as the callback. This injects

// content.js into the current tab's HTML

eventPage.getPageDetails(onPageDetailsReceived);

});

});

You have to declare your background page (event.js) and relative permissions in manifest.json, the sample file is as follows: