1

I'm trying to create a chrome extension that interacts with youtube. It loads the content script, which is then supposed to inject the experiment.js script from web_accessible_resources. None of my code from experiment.js works.

I've followed this as reference: Insert code into the page context using a content script

manifest.json

{
    "version": "1.0",
    "manifest_version": 2,
    "permissions": ["tabs", "https://*/*"],
    "content_scripts": [{
        "js": ["contentscript.js"],
        "matches": [ "https://*.youtube.com/*", "http://*.youtube.com/*"]
    }],
    "web_accessible_resources": ["experiment.js"],
    "browser_action": {
      "default_icon": "icon.png"
    }
}

contentscript.js

var s = document.createElement('script');
s.src = chrome.extension.getURL('experiment.js');

s.onload = function() {
    this.parentNode.removeChild(this);
};

(document.head||document.documentElement).appendChild(s);

experiment.js

alert('loaded');
console.log('loaded');

EDIT: I just used another solution by including the code from experiment.js into contentscript.js in an array and joining each line. The process is referred to as "Method 2" in the reference post I added earlier.

Community
  • 1
  • 1
Swills
  • 153
  • 2
  • 16

1 Answers1

1

Basically the problem was caused by content scripts limitations. For security reasons (I guess) content scripts can't use variables or functions defined by web pages or by other content scripts. It's called sandboxing.

When you add new script to the page by creating new <script> element you add this script to the page's sandbox. Therefore content script couldn't see the one added to the page, even if it is your extension's code.

Simplest solution is you quick fix. You just need to add the script to the manifest file or using programmatic injection.

Besides their limitations, content scripts can use shared DOM to communicate with the page. In this case you could add script to the page using <script> tag and communicate with content script using window.postMessage.

Pawel Uchida-Psztyc
  • 3,735
  • 2
  • 20
  • 41
  • No, this is not an answer for this question. As you can see, `experiment.js` is not using _any_ variables. And OP is aware of the isolated worlds and injects explicitly to interact with the page. – Xan Sep 02 '15 at 20:00