I\'m having a heck of a time trying to get code in my content script to talk to my panel. (This extension adds a new panel to the Dev Tools.) From my content script I can do
To Establish connection between Devtools Page and multiple content script pages, Background Page is used as a mediator. So, idea is to have a channel from devtools
to background
and from background
to content scripts
. This is a generic method needed to handle variable nature of content scripts execution time
.
You can use following script as a reference for communication between devtools.js
to content scripts
.
manifest.json
Registered background
,devtools
and content scripts
to manifest file
{
"name": "Inspected Windows Demo",
"description": "This demonstrates Inspected window API",
"devtools_page": "devtools.html",
"manifest_version": 2,
"version": "2",
"permissions": [
"experimental",
"tabs"
],
"background": {
"scripts": [
"background.js"
]
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"myscript.js"
]
}
]
}
devtools.html
Registered devtools.js
to comply with CSP
<html>
<head>
<script src="devtools.js"></script>
</head>
<body></body>
</html>
devtools.js
//Created a port with background page for continous message communication
var port = chrome.extension.connect({
name: "Sample Communication" //Given a Name
});
//Posting message to background page
port.postMessage("Request Tab Data");
//Hanlde response when recieved from background page
port.onMessage.addListener(function (msg) {
console.log("Tab Data recieved is " + msg);
});
myscript.js
//Handler request from background page
chrome.extension.onMessage.addListener(function (message, sender) {
console.log("In content Script Message Recieved is " + message);
//Send needed information to background page
chrome.extension.sendMessage("My URL is" + window.location.origin);
});
background.js
//Handle request from devtools
chrome.extension.onConnect.addListener(function (port) {
port.onMessage.addListener(function (message) {
//Request a tab for sending needed information
chrome.tabs.query({
"status": "complete",
"currentWindow": true,
"url": "http://www.google.co.in/"
}, function (tabs) {
for (tab in tabs) {
//Sending Message to content scripts
chrome.tabs.sendMessage(tabs[tab].id, message);
}
});
});
//Posting back to Devtools
chrome.extension.onMessage.addListener(function (message, sender) {
port.postMessage(message);
});
});
You can see http://www.google.co.in/
being received in devtools
page
You can refer the following documentation for further information.