I want to create a simple native messaging chrome extension. That is , I need to communicate with the chrome extension through a web and a the web app through the extension.
But when the port message is console.log , no output is given. But the value send by the content script via request.value is displayed. How to fix this problem.
I tried to open vs code here by clicking a button inserted into the web page through the content script and it was successful. Now I want to pass a message from the chrome extension to web page using Native messaging.
manifest.json
{
"name": "Native Messaging Ex",
"version": "1.0",
"description": "Native messaging",
"background": {
"scripts": ["background.js"]
},
"manifest_version": 2,
"permissions": ["nativeMessaging"],
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"run_at": "document_idle",
"js": ["contentScript.js"]
}
],
"browser_action": {
"default_popup": "popup.html"
}
}
vs.bat
@echo off
start code
vs.json
{
"name": "com.vscode",
"description": "My Application",
"path": "vs.bat",
"type": "stdio",
"allowed_origins": [
"chrome-extension://bmnmbagcjohegbabfgkhhmdgph/"
]
}
contentScript.js
// runs on the matching webpage
var button = document.createElement('button');
var buttonTextNode = document.createTextNode('Click me to trigger something');
var body = document.querySelector('body');
button.appendChild(buttonTextNode);
body.appendChild(button);
// Event listener
button.addEventListener('click', function () {
chrome.runtime.sendMessage({
type: 'info',
value: 'Hello World from other planet!',
});
});
background.js
// connect to the native messaging app
chrome.runtime.onMessage.addListener(function (request, senders) {
if (request.type === 'info') {
var port = chrome.runtime.connectNative('com.vscode');
console.log(request.value); // Hello World from other planet!
port.postMessage(request.value);
port.onMessage.addListener(function (message) {
console.log(message); // Nothing here
});
port.onDisconnect.addListener(function () {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
}
});
}
});