0

For some reason the injected script will not get what the content script is sending it.

document.dispatchEvent(new CustomEvent('ToFBScript',{detail: {data: "Hello    World"}}));

//Injecting Script
var s = document.createElement('script');
s.src = chrome.extension.getURL('fbscriptforextension.js');
(document.head||document.documentElement).appendChild(s);
s.onload = function(){
 s.parentNode.removeChild(s);
};

My contentScript

var storage;
document.addEventListener('ToFBScript',function(e){
storage = e.detail.data;
console.log(storage);
});

My Injected Script

Victoria
  • 25
  • 1
  • 4
  • Possible duplicate of [Chrome extension - retrieving Gmail's original message](http://stackoverflow.com/questions/9602022/chrome-extension-retrieving-gmails-original-message) – Haibara Ai Jul 08 '16 at 00:31
  • Besides above link, http://stackoverflow.com/questions/9915311/chrome-extension-code-vs-content-scripts-vs-injected-scripts also could help understand content scripts vs injected scripts. – Haibara Ai Jul 08 '16 at 00:32
  • Quick note: your last 2 edits invalidated my answer. Editing a question substantially AFTER you receive answers is usually a bad idea; I would ask you to roll those back and ask a new question if you still have problems. – Xan Jul 11 '16 at 11:46

1 Answers1

1

You're trying to set the data property of CustomEvent, but you can only set detail. Fortunately, you can set it to anything JSON-serializable.

document.dispatchEvent(new CustomEvent('ToFBScript', {detail: {data: g}}));

/* ... */

document.addEventListener('ToFBScript', function(e) {
  storage = e.detail.data;
}
Xan
  • 74,770
  • 16
  • 179
  • 206
  • I have done this and put console.log(storage); withing the event listener in the injected script, but nothing even prints out and I think that for some reason the injected script is just not getting the event. Could it have to do with when each script loads or is injected? – Victoria Jul 08 '16 at 18:41
  • I edited my code above show the block of code for content script shows the injection of the injected script – Victoria Jul 08 '16 at 19:10
  • Well, _duh_, you're dispatching the event way before anything can listen to it. You need to move messaging code to the `onload` handler. – Xan Jul 08 '16 at 20:51
  • Ahhh okay, thank you! But one more question, I want to store the e.detail.data into a variable inside of the document.addEventListener, and I already declared the variable outside the document.addEventListener() but whenever I try to print storage out outside of the document.addEventListener() it is undefined and acts as if storage = e.detail.data; never happened once outside the document.addEventListener() – Victoria Jul 11 '16 at 00:53