1
votes

I want to pass the page script form data to index.js in my extension. What is the way to do it? I am trying to send it through content-script.js. To do this I am including my content-script.js file into the page-script. The content-script.js contains these lines of code-

function getInput(){
   var url = document.getElementById('addr').value;
   self.port.emit("addr",url);
}

Now from the page-script submit button I am calling getInput() function. But self.port.emit does not work here.

1

1 Answers

1
votes

I have found out the solution. This can be done by creating DOM events.

In the page-script I have created a custom DOM event like this-

add.html->
<html>
<head>
<script>
 function sendMessage() {
    var url = document.getElementById('addr').value;
    //console.log(url);
    var event = document.createEvent('CustomEvent');
    event.initCustomEvent("msg", true, true, url);
    document.documentElement.dispatchEvent(event);
  }
</script>
</head>
<body>

<form>
<input type="text" id="addr" name="addr">
<button onclick="sendMessage()">Add</button>      
</form>

Next the helper.js listens for the new event and retrieves the message.

helper.js-
window.addEventListener("msg", function(event) {
var url = JSON.stringify(event.detail);
self.postMessage(url);
}, false);

Finally the index.js "panel" code looks like this-

var panels = require("sdk/panel");
var panel = panels.Panel({
    width: 200,
    height: 200,
    contentURL: "./page.html",
    contentScriptFile: "./helper.js",
 onHide: handleHide,
 onMessage: function(url) {
 console.log(url); // displays the user input
 }
});

Working fine. Is there other way to do this? Is this efficient one?

Also working fine with self.port.emit() and panel.port.on().