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

3
  • Possible duplicate of Chrome extension - retrieving Gmail's original message Commented Jul 8, 2016 at 0:31
  • Besides above link, stackoverflow.com/questions/9915311/… also could help understand content scripts vs injected scripts. Commented Jul 8, 2016 at 0: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. Commented Jul 11, 2016 at 11:46

1 Answer 1

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; } 
Sign up to request clarification or add additional context in comments.

4 Comments

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?
I edited my code above show the block of code for content script shows the injection of the injected script
Well, duh, you're dispatching the event way before anything can listen to it. You need to move messaging code to the onload handler.
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()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.