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

时间:2017-06-26 13:19:52

标签: 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>

我的扩展程序代码为:

$(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...

});

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

同时,如果我尝试在Chrome的开发者控制台中查看console.log(window.netflix),我会看到结果。 console.log(typeof(window.netflix))返回object。但是在此Chrome浏览器扩展后仍然看不到此变量并返回undefined

我相信我会想念一些简单但又无法理解的东西。

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

P.S。我也检查了这个答案,但它不适合我: chrome extension: run script after page has finished loading javascript

1 个答案:

答案 0 :(得分:3)

据我所知(感谢@wOxxOm) - Chrome扩展程序中的内容脚本在隔离世界中运行,因此要访问网页的变量,您需要将目标代码插入网站中。使用内容脚本的页面。

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

    var s = document.createElement('script');
    s.src = chrome.extension.getURL('content.js');
    s.onload = function() {
      this.remove();
    };
    (document.head || document.documentElement).appendChild(s);
    
  2. 您需要对manifest.json进行更改:

    ...
    "content_scripts": [
       {
         "matches": [ "*://www.yoursite.com/*" ],
         "js": ["start.js"],
         "css": [ "style.css"]
       }
     ],
     "web_accessible_resources": ["content.js"],
     ...
    
  3. 将目标代码放入content.js。现在,您可以访问content.js内网站页面中的任何变量。

相关问题