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.

2
  • Any errors shown in the console? Commented Aug 31, 2015 at 23:46
  • I didn't come across any errors. I just went with a quick fix. Commented Sep 1, 2015 at 0:29

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.