我创建了一个支持本机消息传递的chrome扩展。扩展程序正常运行,使用chrome:// apps运行扩展程序。现在我尝试从网页触发扩展程序,只有当我从chrome:// apps打开我的扩展程序时它才有用,但如果我没有打开扩展程序它就不起作用,而扩展程序安装在chrome中。
mainifest.json:
{
"name": "Native Messaging Example",
"version": "1.0",
"manifest_version": 2,
"description": "Send a message to a native application.",
"app": {
"launch": {
"local_path": "main.html"
}
},
"icons": {
"128": "icon-128.png"
},
"permissions": [
"nativeMessaging"
],
"content_scripts": [{ "matches": ["<all_urls>","http://*/*","https://*/*"], "js": ["contentscript.js"], "run_at": "document_start"}]
}
内容脚本:
document.addEventListener("hello", function(data) {
chrome.runtime.sendMessage("test");
})
Background.js
var port = null;
var getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}
function appendMessage(text) {
document.getElementById('response').innerHTML += "<p>" + text + "</p>";
}
function updateUiState() {
if (port) {
document.getElementById('connect-button').style.display = 'none';
document.getElementById('input-text').style.display = 'block';
document.getElementById('send-message-button').style.display = 'block';
} else {
document.getElementById('connect-button').style.display = 'block';
document.getElementById('input-text').style.display = 'none';
document.getElementById('send-message-button').style.display = 'none';
}
}
function sendNativeMessage() {
message = {"text": document.getElementById('input-text').value};
port.postMessage(message);
appendMessage("Sent message: <b>" + JSON.stringify(message) + "</b>");
}
function onNativeMessage(message) {
appendMessage("Received message: <b>" + JSON.stringify(message) + "</b>");
}
function onDisconnected() {
appendMessage("Failed to connect: " + chrome.runtime.lastError.message);
port = null;
updateUiState();
}
function connect() {
var hostName = "com.google.chrome.example.echo";
appendMessage("Connecting to native messaging host <b>" + hostName + "</b>")
port = chrome.runtime.connectNative(hostName);
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
updateUiState();
}
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
alert("message received");
var hostName = "com.google.chrome.example.echo";
appendMessage("Connecting to native messaging host <b>" + hostName + "</b>")
port = chrome.runtime.connectNative(hostName);
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
});
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('connect-button').addEventListener(
'click', connect);
document.getElementById('send-message-button').addEventListener(
'click', sendNativeMessage);
chrome.runtime.sendMessage("test");
updateUiState();
});
page.html中
<html>
<head></head>
<body>
<script>
var go = function() {
var event = document.createEvent('Event');
event.initEvent('hello');
document.dispatchEvent(event);
}
</script>
<a href="javascript:go();">Click me</a>
</body>
</html>