gpt4 book ai didi

javascript - 在 Chrome 扩展中抓取 DOM 值

转载 作者:行者123 更新时间:2023-12-03 00:20:36 26 4
gpt4 key购买 nike

我正在使用 Chrome 扩展程序抓取用户的页面。该扩展程序接收一个 API 响应,其中包含正确的 document.querySelector(x) 命令。然后它尝试定位该元素, trim 其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 响应中的 querySelector
  • 无法在 DOM 中找到该元素(即控制台没有显示“存在于 DOM 中”)
  • 但是当我键入附加了 .innerText 的相同命令时,我得到“Jane”,即正确的值。

enter image description here

我的猜测是 API 响应(一个 JSON 对象)没有被正确理解为 JavaScript。但我不知道如何转换它。

最佳答案

您有一个值为 "document.querySelector('#txtFName')" 的字符串,而不是实际的函数调用。您必须使用 eval 或类似功能。

评估:
const el = eval(message[key].selector);

免责声明:由于存在安全风险,通常不建议使用这些功能。例如,如果某些字符串源自用户输入,则恶意攻击者将能够注入(inject)任意代码,然后这些代码可能会被攻击。在其他用户的浏览器上运行。如果这是唯一可行的解​​决方案,您应该清理输入。

为了完整性,我还将提到这个替代方案。 Function constructor可用于创建一个以字符串作为主体的新函数。这与 eval 具有相同的安全风险。

关于javascript - 在 Chrome 扩展中抓取 DOM 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54329926/

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