user3411789
user3411789

Reputation: 45

Access DOM var from content.js script

I'm trying to access a global var (timer) on a webpage using the content.js script via my google chrome extension. However, everytime it returns undefined, even though I can easily access it via the developer console.

var mySocket;
console.log('content.js');

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    switch(request.task){
        case "socketInjection":
            window.setTimeout(
            function(){ console.log(timer);}, 5000);

            break;
    }
  });

Im using a setTimeout routine there, to make sure the page has loaded completely (which it should've anyways).

Anyone has a solution? Thanks in advance, Daniel

Upvotes: 0

Views: 104

Answers (2)

jpolitz
jpolitz

Reputation: 699

The extension and the content script both have a different global scope than the page, so if there's something like timer = 5 in the extension or on the page, that isn't visible in the content script.

See

https://developer.chrome.com/extensions/content_scripts

However, content scripts have some limitations. They cannot:

  • Use variables or functions defined by their extension's pages
  • Use variables or functions defined by web pages or by other content scripts

This answer discusses some options:

Share in-memory objects in Chrome extension content scripts?

Upvotes: 1

user3411789
user3411789

Reputation: 45

I missunderstood the context of content.js

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. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.

Isolated worlds allow each content script to make changes to its JavaScript environment without worrying about conflicting with the page or with other content scripts. For example, a content script could include JQuery v1 and the page could include JQuery v2, and they wouldn't conflict with each other.

Another important benefit of isolated worlds is that they completely separate the JavaScript on the page from the JavaScript in extensions. This allows us to offer extra functionality to content scripts that should not be accessible from web pages without worrying about web pages accessing it.

Upvotes: 0

Related Questions