I am trying to create a hybrid app using only GeckoView as webview. I am following this link to establish communication between native and HTML/Javascript. I am using Connection-based messaging. So far I am able to receive a message from native and send the message back to the native from background script. But I am not able to do the following :
Show the message from background script : I have tried to showthe value from custom event inside background script but its not working. Code is as follows :
function eventHandler(element){
element.dispatchEvent(event);
element.addEventListener('build', function (e) {
console.log("Inside event listener");
element.innerHTML="change";
let text = document.getElementById("text").innerText;
console.log("Main js executed :::::"+ text);
}, false);
}
I have tried to send the message from Content script but its not working either as I am getting browser is undefined.
browser.runtime.onMessage.addListener(
function (request, sender){
console.log("Message received");
});
I have tried to to use chrome instead of browser but its giving the same result. I am using 78.0.20200601093812 version of GeckoView. My manifest for only background script is as follows :
{
"manifest_version": 2,
"name": "messaging",
"version": "1.0",
"description": "Example messaging web extension.",
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self';",
"browser_specific_settings": {
"gecko": {
"id": "message@example.com"
}
},
"content_scripts": [
{
"matches": ["resource://android/assets/www/messaging/main.html"],
"js": ["messaging.js"]
}
],
"background": {
"scripts": ["jquery-3.3.1.min.js","background.js", "main.js"],
"page": "main.html",
"persistent": true
},
"permissions": [
"nativeMessaging",
"geckoViewAddons",
"nativeMessagingFromContent",
]
}
If the HTML code is part of your extension you can use extension pages. Extension pages have full access to the WebExtension API. All you need to do is load the page using the web-extension://[UUID]
path, something like this should work
session.loadUri(extension.metaData.baseUrl + "/main.html");
where main.html
is a HTML file inside the extension folder, and extension
is the extension object you get back from installBuiltIn
.
Then in the main.html
add a script like this
<script src=main.js></script>
and in main.js
you can connect to the app using the same code that you have in the guide:
// Establish connection with app
let port = browser.runtime.connectNative("browser");
port.onMessage.addListener(response => {
// Let's just echo the message back
port.postMessage(`Received: ${JSON.stringify(response)}`);
});
port.postMessage("Hello from WebExtension!");