Sharavanakumaar Murugesan Sharavanakumaar Murugesan - 1 month ago 7
Javascript Question

Firefox WebExtensions send message from browser to extension and get response in call back function

I'm trying to convert my Chrome extension to a FireFox WebExtensions . I am having an issue to communicating between my webpage to the background script.
From content script I am injecting some functions into browser page. That functions need to call browser extension and get response for that.


manifest.json



{
"manifest_version" : 2,
"name" : "Sample",
"description" : "Sample",
"version" : "1.0",

"icons" : {
"48" : "icons/link-48.png"
},

"applications" : {
"gecko" : {
"id" : "sample@sss.com",
"strict_min_version" : "48.0"
}
},

"permissions" : ["notifications", "alarms", "storage"],

"background" : {
"scripts" : [
"js/jquery.js",
"background-script.js"
]

},
"web_accessible_resources" : ["js/content.js"], // Not working in firefox
"externally_connectable" : {
"matches" : [
"http://localhost/*",]
},
"content_scripts" : [{
"matches" : ["<all_urls>"],
"js" : ["js/jquery.js",
"js/script.js",
"content-script.js"
],
"run_at" : "document_start"
}
],
"default_locale" : "en"
}



content-script.js


var port = chrome.runtime.connect();

window.addEventListener("message", function(event) {

if (event.source != window)
return;

if (event.data.type && (event.data.type == "FROM_PAGE")) {
console.log("Content script received: " + event.data.text);
chrome.runtime.sendMessage({
hello: 1
},function (response)
{
//Need to send response back to browser
});
}
}, false);



background-script.js


chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
alert('bg');
var response_Text = '-1';

if (request.hello) {
console.log('hello received');
sendResponse("213");
}
});



browser page


window.postMessage({ type: "FROM_PAGE", text: "Hello from the webpage!" },"*");


I am using the window.postMessage to send some content.

Is it possible to get callback value for this function or any method available to send message to extension from webpage and get response?

Answer

Browser Page

Convert your callback to String and attach with detail parameter

var callbackstring=callback.toString(); *

and send like

var evt = document.createEvent("CustomEvent");
evt.initCustomEvent("eventname", true, true, {callback:callbackstring});
window.dispatchEvent(evt);

Content Script

Retrieve the callbackstring from event object like

var callbackstring=event.detail.callback;

Use eval function and convert the string to function

eval("var callback="+callbackstring);

Now you can trigger your callback easily in the listener

callback(response);
Comments