For this task you need to use onMessage, sendMessage, and query. The onMessage
is a method of chrome.runtime, sendMessage
, and query
are both methods of tabs.
Manifest
The first thing you want to do is add the tabs permission to your manifest file.
"permissions": [
"tabs"
],
Popup HTML
For the popup page you need to separate your Javascript from your html page. You can no longer add inline Javascript to the popup page. So create an HTML and Javascript file. For this example I will use an anchor tag by giving it an ID. When clicked this will trigger the sending of data.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Popup</title>
</head>
<body>
<div id="mainPopup">
<h1>Popup</h1>
<p>
<a href="#" id="email-filler">Email</a>
</p>
</div>
<script src="popup.js"></script>
</body>
</html>
Popup Javascript
Now when the anchor tag is clicked an onClick
event is triggered, and this sends your data to the content script.
// tab options
var tabOptions = {
active: true,
currentWindow: true
};
// when button is clicked
document.getElementById("email-filler").onclick = function () {
// we use tabs query to find the id of the tab you wish to send data to
chrome.tabs.query(tabOptions, function (tab) {
// parameter 1: id of the tab you are sending data to
// parameter 2: the data you are sending to the tab
chrome.tabs.sendMessage(tab[0].id, "joe@joebloggs.com");
});
};
Content Script
Lastly add the following to your content script. The request variable contains the data you are sending from the popup page.
chrome.runtime.onMessage.addListener(onRequest);
function onRequest(request, sender, sendResponse) {
console.log(request);
document.getElementsByName("SOME-NAME")[0].value = request;
}