问题描述
Noobie 在这里......试图找出一些东西。我正在研究这个 chrome 扩展,我在页面上注入了一些 html,下一步是读取所有页面,找到一些文本并将其添加为我注入的选择输入字段的选项。这是我的清单的一部分:
"content_scripts" : [
{
"run_at": "document_end","js" : [
"js/main.js"
],"css" : [
"css/main.css"
],"matches" : ["https://streamyard.com/*"]
}
这是我的内容脚本:
var isHtmlDeployed = false;
var x=0;
//read the html file
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("GET",chrome.extension.getURL('../includes/scenesettings.html'),true);
xhr.send();
fillLayoutCombo();
//Inject the html file
function handleStateChange(){
if (xhr.readyState=4 && xhr.responseText !='' &xhr.status==200 && isHtmlDeployed==false){
var newHtml = document.createElement('div');
newHtml.innerHTML = xhr.responseText;
document.body.appendChild (newHtml);
isHtmlDeployed = true;
}
}
//add options
function fillLayoutCombo(){
for(var i=0;i<=9;i++){
var opt = document.createElement('option');
opt.value = 'Solo Layout';
opt.innerHTML = 'Solo Layout';
console.log('select[id="cboSceneType'+i+'"]');
select = document.querySelector('[id="cboSceneType'+i+'"]');
select.appendChild(opt);
}
}
我不明白为什么当我使用 fillLayoutCombo() 函数时,我注入的 html 仍未加载,所以我最终选择 = document.querySelector('[id="cboSceneType'+i+'"]') ;为空并出现错误。即使我的清单说脚本应该在页面加载结束时运行。我能做些什么来解决这种情况(在写作时我刚刚意识到 'document_end' 什么都不做,毕竟 html 只会在脚本运行时注入,所以我在异步 xmlhttprequest 上有问题吗?如何解决?)
感谢您的帮助。
解决方法
只是为了在解决方案中设置人员。我只是将调用移至fillLayoutCombo 作为handleStateChange 的最后一步。 问题解决了
谢谢你们!