javascript Chrome 扩展加载行为
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12770238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Chrome extension onload behaviour
提问by cristian.petroaca
I am developing a settings page for a chrome extension. In my options.js file I want to initalize the settings with some default values and I use window.onload = initSettings();
for that. In my initSettings()
function I am trying to access an input from the DOM via document.getElementById("someId")
. But this call always returns null
. I thought that the window.onload
event is fired after all of the DOM elements are in place.
我正在为 chrome 扩展开发一个设置页面。在我的 options.js 文件中,我想用一些默认值初始化设置,然后我使用window.onload = initSettings();
它。在我的initSettings()
函数中,我试图通过document.getElementById("someId")
. 但是这个调用总是返回null
。我认为window.onload
在所有 DOM 元素都到位后会触发该事件。
What am I doing wrong?
我究竟做错了什么?
回答by enhzflep
I have this in the top of my options.js file - It's been so long since I last played with extensions, I can't be sure it's of any help. Worth a shot..
我在 options.js 文件的顶部有这个 - 自从我上次玩扩展已经很久了,我不能确定它有什么帮助。值得一试..
// fires when script is first loaded
// can't do onInit directly here, because the DOM hasn't been loaded for options.html yet
// we just set an event listener for document.DOMContentLoaded - In that handler we can call onInit
document.addEventListener('DOMContentLoaded', onInit, false);
回答by DBJoran
I needed to run a piece of code when my chrome extension was opened, I used the following code:
当我的 chrome 扩展程序打开时,我需要运行一段代码,我使用了以下代码:
document.addEventListener("DOMContentLoaded", function(){ checkCheckBoxes(); }, false);
where "checkCheckBoxes" is the Javascript function that gets called.
其中“checkCheckBoxes”是被调用的 Javascript 函数。