0

I am trying to have a function in an injected script which gets some paramaters and forwards them to the content script, which in turn forwards it to the background script. I have read Chrome extension - retrieving Gmail's original message, but applying that code does not work properly. I have the following code which is injected.

   window.postToContentScript = function(cmd, payload)  {
        var obj = {"command": cmd, "data": payload};        
        console.error(obj);
        document.dispatchEvent(new CustomEvent('MyCustomEvent', {
            detail: obj,
        })); 
    }

When called, it logs my passed parameters to the console (so that's not an issue..). In the content script, I have the following code:

document.addEventListener("MyCustomEvent", function(e) {
    console.error(e);
})

I would guess that it should actually contain an object with properties command and data, however the detail property of the event is just null. I realize that one way of approaching this is to add e.g. a hidden textarea into the document, filling that and subsequently reading it from the content script. However, this hardly seems as elegant as appending details to an event..

Any thoughts?

Community
  • 1
  • 1
sqrtsben
  • 246
  • 1
  • 7
  • btw - tried using window.dispatchEvent and window.addEventListener - didn't work either – sqrtsben May 26 '14 at 21:10
  • Have you tried the recommended [method of `window.postMessage`](https://developer.chrome.com/extensions/content_scripts#host-page-communication) instead of custom events? – Xan May 26 '14 at 21:15
  • I realize that this works, however it also might trigger any onMessage listener there is in the document itself (which I don't want to do to ensure minimum impact on the page itself) – sqrtsben May 26 '14 at 21:19
  • Works fine for me on Chromium 34.0.1847.137. Are you sure that the data you're trying to pass is simple? E.g. it must NOT be a DOM object, a function, etc. Otherwise `detail` will be `null`. – Rob W May 26 '14 at 21:54
  • Ok, found out that this is actually an issue of an older version of Chromium. However, I need to use this version since it's patched - so I guess that explains it :( – sqrtsben May 26 '14 at 22:25
  • Voted to close as "no longer can be reproduced". – Xan May 27 '14 at 08:38

0 Answers0