首先,我不是程序员。我根本不懂 Javascript。 我正在尝试创建一个 Chrome 扩展程序,通过获取网页上的特定字符串来修改我的浏览器选项卡的标题。我知道如何创建 Chrome 扩展(只是勉强知道),我只需要修改 Javascript 来完成我想要的操作(我不知道如何做)。
我在网上找到了以下脚本,并尝试修改它,但不知道如何让它工作。这是脚本:
// Fire this event any time the mouse is moving. Sucks for performance, but it's a better experience
document.addEventListener("mousemove", function() {
// This will get us the banner
let bannerTextElements = document.getElementsByClassName("dijitReset dijitInputField dijitInputContainer");
console.log(bannerTextElements);
console.log(bannerTextElements[0]);
if (bannerTextElements[0]) {
console.log("ok!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
console.log(bannerTextElements[0].innerHTML);
// This will get us the text
let bannerTextLine = bannerTextElements[0].getElementsByClassName("dijitReset dijitInputInner");
console.log(bannerTextLine);
document.title = bannerTextLine[0].innerHTML
}
},假);
这是在开发者模式下查看的网站。我想获取文本“blahhhh”并将其用作浏览器选项卡的标题。
下面是一个不同的网页,这里的区别是“div class”名称会改变。这些类中的数字将更改为不同的数字,但结构和整体名称保持不变。例如,“ms-Button-label label-549”可能会更改为“ms-Button-label label-640”。每当您刷新页面时都会发生这种情况。我发现“viewport”id 名称并没有改变,所以我想我们是否可以使用它作为引用,然后查看嵌套的 div 类并引用它们并提取值(在本例中为 Crystal Mountain)。
最佳答案
修复代码
您已获得所需的 95%。
您现在缺少的一件事是 input
元素不具有“innerHTML”(这就是为什么它没有像这样关闭: <input>renderedText</input>
)。相反,您想检查它的值:
document.title = bannerTextLine[0].value;
一些改进:
按 ID 搜索
您有一个明确定义的输入,可以通过使用 id 查找它来更轻松地获得它:
let bannerTextLine = document.getElementById('lanDeviceIndex_searchBox');
最终结果:
const bannerTextLine = document.getElementById('lanDeviceIndex_searchBox');
bannerTextLine.addEventListener("blur", function() {
if (bannerTextLine != null) {
document.title = bannerTextLine.value;
}
});
这是完整的JS代码。请注意,我将事件更改为模糊,该事件在离开表单时激活,这应该最适合您的情况。
关于Chrome 扩展程序的 Javascript 帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60699403/