从 content.js 脚本访问 DOM var

Access DOM var from content.js script

我正在尝试通过我的 google chrome 扩展程序使用 content.js 脚本访问网页上的全局变量(计时器)。 然而,每次它 returns 未定义,即使我可以通过开发者控制台轻松访问它。

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;
    }
  });

我正在那里使用 setTimeout 例程,以确保页面已完全加载(无论如何它都应该加载)。

有人有解决办法吗? 提前致谢,丹尼尔

我误解了 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.

扩展和内容脚本都具有与页面不同的全局范围,因此如果页面上的扩展 中有类似 timer = 5 的内容,那在内容脚本中不可见。

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

这个答案讨论了一些选项:

Share in-memory objects in Chrome extension content scripts?