1

I'm trying to inject a script to the page inside a content-script.

The injected script should define an object abc onto the window-object. However, after the injected script is loaded, trying to read from the content-script results in window.abc = undefined

Could this be due to content-scripts living in isolated environments? On first thought this would seem weird, as I would expect the content-script and the script dynamically injected from the content-script to live in the same environment (and thus share the same window object)

Background: as part of an extension I need to load a content-script on a wide variety of pages. It seems a complete waste of bandwidth/performance to have to load big scripts for every one of these pages even if the extension might not be used on that page to begin with. Therefore, I'd like the content-script be as lightweight as possible and only load in (lazy load) the heavier scripts (using injection as described) once the user has indicated he wants to use the extension on said page. (by picking up some event such as clicking the extension icon)

Geert-Jan
  • 18,623
  • 16
  • 75
  • 137

1 Answers1

0

Your assumption is correct. It is very clearly stated in the documentation, that you even linked yourself:

Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on.

Script that runs directly on the page uses the page's environment (window), even if you injected it into the page from your content script.

Debugging tip: Chrome Developer Tools Console allows you to switch between the page context and a content script's context in the frame selection dropdown. You should be able to see that window.abc is defined in the page's (probably top) window, but not in the content script's window.

I am not sure what your exact objective is, but if you want to execute something on a page after a click on your extension icon, you can accomplish that by programmatic injection. There is no need to inject anything into the page beforehand.


Further read on SO:

Contexts and methods for communication between the browser action, background scripts, and content scripts of chrome extensions?

Building a Chrome Extension - Inject code in a page using a Content script

Community
  • 1
  • 1
Petr Srníček
  • 2,296
  • 10
  • 22
  • > Script that runs directly on the page uses the page's environment (window), even if you injected it into the page from your content script. Above wasn't clear to me. Thanks – Geert-Jan May 23 '16 at 06:17