Javascript 在Chrome扩展中删除DOM值
我正在用一个Chrome扩展来抓取一个用户的页面。扩展接收一个API响应,其中包含正确的Javascript 在Chrome扩展中删除DOM值,javascript,google-chrome-extension,Javascript,Google Chrome Extension,我正在用一个Chrome扩展来抓取一个用户的页面。扩展接收一个API响应,其中包含正确的document.querySelector(x)命令。然后,它尝试定位该元素、修剪其innerText属性或获取其value属性: //I've removed some additional fields here to focus on the one I'm currently testing message = { txtFName: { selector: fieldmap.Ats
document.querySelector(x)
命令。然后,它尝试定位该元素、修剪其innerText属性或获取其value属性:
//I've removed some additional fields here to focus on the one I'm currently testing
message = {
txtFName: {
selector: fieldmap.AtsMapping[5].firstName,
value: null
}
//line 10450 is the one below
console.log(fieldmap.AtsMapping[5].firstName);
Object.keys(message).forEach((key) => {
const el = message[key].selector;
if (el) {
console.log("Exists in DOM")
if(el.innerText && el.innerText.length > 0) {
console.log("Has inner text property");
message[key].value = el.innerText.trim();
}
else {
console.log("Doesnt have inner text");
message[key].value = el.value;
}
}
});
请注意,我的控制台:
- 显示API响应中的查询选择器
- 在DOM中找不到元素(即控制台没有说“存在于DOM中”)
- 但是当我键入附加了.innerText的相同命令时,我得到了正确的值“Jane”
我的猜测是API响应,一个JSON对象,没有正确地理解为JavaScript。但是我不知道如何转换它。您有一个值为“document.querySelector(“#txtFName”)”的字符串,而不是实际的函数调用。您必须使用
eval
或类似功能
评估:const el=eval(消息[key]。选择器)代码>
免责声明:由于存在安全风险,通常不建议使用这些功能。例如,如果某些字符串来自用户输入,恶意攻击者将能够注入任意代码,然后这些代码可以在其他用户的浏览器上运行。如果这是唯一可行的解决方案,您应该对输入进行消毒
为了完整起见,我还将提到这个替代方案。可用于创建以字符串作为主体的新函数。这与eval
具有相同的安全风险。看起来您有一个值为的字符串“document.querySelector('#txtFName')”
不是实际的函数调用。似乎您必须使用eval
或将字符串作为函数调用进行求值。eval工作得非常好!谢谢既然成功了,我就把它作为答案贴出来。很乐意帮忙。