0

I'm trying to make a simple Chrome extension that controls Youtube. I injected the script that directly controls Youtube with Method 1 of Insert code into the page context using a content script. This is how the injected script looks like.

control.js

var player = document.getElementById("movie_player");

//Do something

document.addEventListener('Remote2Buffer', function(e){
    alert(e.detail);
});

And on a content_script file named buffer.js, I wanted control.js to receive information from it. So I sent the 'Remote2Buffer' event from buffer.js. But the alert that's on control.js isn't working, which implies that the data wasn't sent as intended. This is what buffer.js looks like.

buffer.js

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

var send ='plz work';
document.dispatchEvent(new CustomEvent('Remote2Buffer', {detail: send}));

Is there a possible way to send data to a injected js file from a content_script .js file, or any other way?

TL;DR: I'm trying to send data to a injected .js file.(The opposite direction of data transmission shown on Chrome extension - retrieving Gmail's original message.) Is it possible? If possible, how should I?

EDIT : I changed buffer.js to

buffer.js

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

var send ='plz work';
window.onload = function(){
        document.dispatchEvent(new CustomEvent('Remote2Buffer', {detail: send}));
};

After changing the code, the alert started to occur, but sometimes it didn't occur. Why does this happen?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user3653206
  • 183
  • 1
  • 2
  • 5
  • Why do you use DOM Events at all? You can just have `buffer.js` detect `control.js` and have them communicate directly. – Halcyon May 19 '14 at 15:48
  • @Halcyon They are in different execution contexts and cannot communicate directly. – Xan May 19 '14 at 15:49
  • 1
    I see. Maybe this is really trivial but you seem to be dispatching the event before `control.js` had it's onload. Can you move the last 3 lines into the `onload` callback? – Halcyon May 19 '14 at 15:54
  • 1
    @Xan removing a ` – rsanchez May 19 '14 at 16:05
  • @Halcyon I put the last 2 lines of buffer.js into window.onload, and the alert is behaving rather strange. Sometimes the alert comes out, and sometimes it doesn't. Do i have to change window to something else? Sorry for the rather stupid question because I'm new to this language:(. – user3653206 May 19 '14 at 16:15

0 Answers0