我在浏览器中运行hello.html
页面,当我按下submit
按钮时,它应该发布一条消息,该消息将在我的chrome devtools扩展中接收并显示在控制台中。但它没有用。
的manifest.json
{
"name": "Network Data",
"version": "1.0.2",
"manifest_version": 2,
"description": "Adds ColdFire support.",
"devtools_page": "devtools.html",
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
],
"content_scripts": [{
"matches": ["http://*/*","https://*/*"],
"js": ["contentscript.js"],
"run_at": "document_start"
}]
}
hello.html的
<html>
<body>
<button id="mybutton">click me</button>
</body>
<script>
document.getElementById("mybutton").addEventListener("click", function() {
window.postMessage({ type: "FROM_PAGE", text: "Hello from the webpage!" }, "*");
alert('button clicked');
}, false);
</script>
</html>
contentscript.js
var port = chrome.runtime.connect();
chrome.runtime.onMessage.addListener("message", function(event) {
// We only accept messages from ourselves
if (event.source != window)
return;
if (event.data.type && (event.data.type == "FROM_PAGE")) {
console.log("Content script received: " + event.data.text);
port.postMessage(event.data.text);
}
}, false);