为了在Devtools 页面和多个内容脚本页面之间建立连接,后台页面用作中介。所以,想法是有一个通道 from devtools
tobackground
和 from background
to content scripts
。这是处理内容脚本的可变性质所需的通用方法execution time
。
您可以使用以下脚本作为 to 之间通信的devtools.js
参考content scripts
。
清单.json
注册background
,devtools
并content scripts
到清单文件
{
"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"
]
}
]
}
开发工具.html
注册devtools.js
符合 CSP
<html>
<head>
<script src="devtools.js"></script>
</head>
<body></body>
</html>
开发工具.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);
});
背景.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);
});
});
输出
您可以在页面中看到http://www.google.co.in/
正在接收devtools
参考
您可以参考以下文档以获取更多信息。