【发布时间】:2017-11-29 08:29:01
【问题描述】:
我正在开发一个 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。
我相信我错过了一些简单的东西,但无法理解到底是什么。
任何想法如何使用扩展脚本从网站访问变量(和对象数据)?
附:我也检查了这个答案,但它对我不起作用: chrome extension: run script after page has finished loading javascript
【问题讨论】:
-
1.内容脚本在孤立的世界中运行,因此您需要Insert code into the page context using a content script 和 2. 如果您的内容脚本以默认设置(
"run_at": "document_idle")运行,则不需要$(document).ready(function() {,3. devtools 控制台有一个其工具栏中的上下文选择器,默认为Top,这意味着页面本身,但如果您将其切换到扩展程序,您将看到页面变量的undefined,就像您的内容脚本一样。 -
似乎是个好建议!现在检查。
标签: javascript google-chrome-extension