Chrome 扩展程序:在加载所有其他页面脚本后运行扩展程序的脚本

Kir*_*zur 3 javascript google-chrome-extension

我正在开发一个 Chrome 扩展程序,我想在加载所有页面脚本后加载它。

网站页面包含这样的代码:

<html>
  <body>
  <div id="main">All body elements, texts, etc...</div>
  <script>
    window.netflix = window.netflix || {};
    netflix.falkorCache = {"genres":"58"}
  </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我的扩展代码是:

$(document).ready(function() {
  launchPlugin();

  function launchPlugin() {
    console.log(typeof(window.netflix));//I have also tried just `netflix`
    if(typeof(window.netflix)!=='undefined'){
      startNetflixPlayer();
    } else{
      setTimeout(
        function(){
          launchPlugin();
        }, 700);
    }
  }

  //other code...

});
Run Code Online (Sandbox Code Playgroud)

但插件永远不会运行,startNetflixPlayer()因为window.netflix总是undefined。我也尝试过检查变量netflix,但它也返回undefined

同时,如果我尝试检查console.log(window.netflix)Chrome 的开发人员控制台,我会看到结果。 console.log(typeof(window.netflix))返回object。但是在这个 Chrome 扩展之后仍然看不到这个变量并返回undefined.

我相信我错过了一些简单的东西,但无法理解到底是什么。

有什么想法如何使用扩展程序的脚本从网站访问变量(和对象数据)?

PS我也检查了这个答案,但它对我不起作用: chrome扩展:在页面完成加载javascript后运行脚本

Kir*_*zur 5

据我了解(感谢 @wOxxOm)\xe2\x80\x93 Chrome 扩展中的内容脚本在孤立的世界中运行,因此要访问页面的变量,您需要使用内容脚本将目标代码插入到网站的页面中。

\n\n
    \n
  1. 您需要start.js使用以下代码创建(将目标代码插入网站页面):

    \n\n
    var s = document.createElement(\'script\');\ns.src = chrome.extension.getURL(\'content.js\');\ns.onload = function() {\n  this.remove();\n};\n(document.head || document.documentElement).appendChild(s);\n
    Run Code Online (Sandbox Code Playgroud)
  2. \n
  3. 您需要进行更改manifest.json

    \n\n
    ...\n"content_scripts": [\n   {\n     "matches": [ "*://www.yoursite.com/*" ],\n     "js": ["start.js"],\n     "css": [ "style.css"]\n   }\n ],\n "web_accessible_resources": ["content.js"],\n ...\n
    Run Code Online (Sandbox Code Playgroud)
  4. \n
  5. 将目标代码放入content.js. 现在您可以从网站的页面访问任何变量content.js

  6. \n
\n


归档时间:

查看次数:

3616 次

最近记录:

8 年,4 月 前