I am trying to send a message from webextension to SDK inside a loop. I need to send the message and get the response in each iteration before the next iteration. However, the code does iterate over all the loop, then sends the reply from the SDK. I do not know whether it behaves correctly and the message from SDK was sent on time? then, why it did not get reply on the right time as well? how to overcome this problem?
What is the reason the code is not running sequentially? How can I overcome this problem (i.e., do not go to the next iteration until receive a reply from the SDK).
The files structure is:
embedding-extension [directory]
- index.js
- package.json
- webextension [directory]
- main.js
- manifest.json
Here is the minimal code:
-
index.js
code:const webExtension = require(“sdk/webextension”);
console.log(“in SDK: inside embedding extension”);// Start the embedded webextension
webExtension.startup().then(api => {
const {browser} = api;
browser.runtime.onMessage.addListener((msg, sender, sendReply) => {
if (msg == “send-to-sdk”) {
console.log(“in SDK: message from webExt has been received”);
sendReply({
content: “reply from SDK”
}); //end send reply
}//end if}); //end browser.runtime.onMessage
}); //end webExtension.startup
-
package.json
code:{
“title”: “testhybrid”,
“name”: “testhybrid”,
“version”: “0.0.1”,
“description”: “A basic add-on”,
“main”: “index.js”,
“author”: “”,
“engines”: {
“firefox”: “>=38.0a1”,
“fennec”: “>=38.0a1”
},
“license”: “MIT”,
“hasEmbeddedWebExtension”: true,
“keywords”: [
“jetpack”
]
} -
In
webextension
directorymain.js
code is:var flag=true;
(function aMethod() {
console.log(“in webExt: inside aMethod”);
for(var x=0; x<2; x++)
{
console.log("loop iteration: "+x);
if(flag==true)
{
console.log(“inside if”);
console.log(“will send message to SDK”);
browser.runtime.sendMessage(“send-to-sdk”).then(reply => {
if (reply) {
console.log("in webExt: " + reply.content);
} //end if
}); //end browser.runtime.sendMessage}//end if flag else { console.log("inside else"); }//end else
}//end for
})();//end aMethod -
In
webextension
directory,manifest.json
code is:{
“manifest_version”: 2,
“name”: “webExt”,
“version”: “1.0”,
“description”: “No description.”,
“background”: {
“scripts”: [“main.js”]
},“permissions”: [
“activeTab”
],“browser_action”: {
“default_icon”: {
“64”: “icons/myicon.png”
},
“default_title”: “webExt”
}
}
The log I am getting is:
testhybrid:in SDK: inside embedding extension index.js:2
in webExt: inside aMethod main.js:3:3
loop iteration: 0 main.js:6:2
inside if main.js:9:9
will send message to SDK main.js:10:9
loop iteration: 1 main.js:6:2
inside if main.js:9:9
will send message to SDK main.js:10:9
testhybrid:in SDK: message from webExt has been received index.js:9
in webExt: reply from SDK
As you can see, I got reply from SDK at the end of the loop. What Ireally need is to send a message and get a reply in each iteration. I appreciate your help.