gpt4 book ai didi

javascript - Chrome 扩展程序 : run extension's script after all other page scripts have loaded

转载 作者:行者123 更新时间:2023-11-29 19:03:34 24 4
gpt4 key购买 nike

我正在开发一个 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

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

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

附注我也检查了这个答案,但它对我不起作用: How to call functions in the original page(tab) in Chrome Extensions

最佳答案

据我了解(感谢 @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 内的网站页面访问任何变量。

关于javascript - Chrome 扩展程序 : run extension's script after all other page scripts have loaded,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44760732/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com