0

Want to send a status value to contentscript.js in chrome extension from the page in the browser, doing it by adding a value to newly created event passing it to extension, but but receiving the value as 'undefined'. code as follows.

page.html

<html>
<head></head>
<body>
<script>
    var go = function() {
    var sam=1;
        var event = document.createEvent('Event',{"details": 1});
        event.foo=sam;
        event.initEvent('hello');
        document.dispatchEvent(event);
    }
</script>
<a href="javascript:go();">Click me</a>
</body>
</html>

I am trying to access the value of 'foo' and 'status'(either of this ), but getting both values as 'undefined'.

contentscript.js

document.addEventListener("hello", function(data) {
    alert("test:foo "+data.foo+":"+data.status);
})

please let me know how to access the value.

rajesh A
  • 373
  • 4
  • 10
  • I wouldn't make it too hard on yourself. just fill up a hidden dom element with stuff, and have your extension read the data from the dom once it loads. You really dont have to do it in pure js – Marc Guiselin Oct 22 '15 at 13:46
  • Hi @Thou Art Amazing, can I get some example links on this topic? – rajesh A Oct 22 '15 at 13:59

1 Answers1

0
 Based on documentation from: [https://developer.chrome.com/extensions/messaging#external-webpage][1]

    - manifest.json

    "externally_connectable": {
      "matches": ["*://<your extension id>/*/page.html"]
    }

    page.html:
    // The ID of the extension we want to talk to.
    var editorExtensionId = "abcdefghijklmnoabcdefhijklmnoabc";

    // Make a simple request:
    chrome.runtime.sendMessage(editorExtensionId, {"details": 1},
      function(response) {
        if (!response.success)
          handleError(url);
      });

    contentscript.js

    chrome.runtime.onMessageExternal.addListener(
      function(request, sender, sendResponse) {
        if (sender.url === blacklistedWebsite)
          return;  // don't allow this web page access
        if (request.details)
          //process message
      });
Nandu
  • 808
  • 7
  • 10
  • Note that this does not work for Firefox, as of FF 54. See https://stackoverflow.com/questions/44592605/firefox-webextension-check-if-my-extension-exists for a possible solution. – Haydentech Aug 01 '17 at 19:42