javascript - 无法从 content.js 文件向浏览器注入代码
问题描述
我正在尝试制作 chrome 扩展,并且在 content.js 文件中编写了某些代码(content.js 文件中包含的代码已粘贴在下面)。
当我运行扩展时,似乎“链接”没有捕获任何对象,并且 href 有 0 个元素。
但是,当我将 content.js 中的整个代码粘贴到网页的控制台时,它可以很好地显示所有所需的链接。在已发布的图片中也证明了这一点。
https://i.stack.imgur.com/LUK1q.png [图片链接]
(图像显示,在我运行扩展程序并检查控制台后,它显示 href 为空,但是当我将 content.js 文件中的代码直接放到控制台时,它显示完全不同的结果。)
您的帮助将不胜感激。
谢谢你。
// start of code
// javascript code written in the content.js file
[The images shows the fact that after I run my extension and check the console,
it shows that href is empty and but when I plate the code from the content.js file directly to the console,
it shows entirely different results.][1]
console.log("chrome extension ready to go");
var className = 'VkhHKd e7EEH nQaZq';
var links = document.getElementsByClassName(className), hrefs=[];
//console.log(links);
for (var i = 0; i<links.length; i++)
{
hrefs.push(links[i].href);
}
console.log(hrefs);
console.log(links.length);
// end of code
解决方案
确保在 manifest.json 中设置了 content.js(如果没有 content.css,则省略该 css 行):
"content_scripts": [
{
"matches": [ "theurlyouwanttoinjectthecontentscripton" ],
"js": ["content.js"],
"css": ["content.css"]
}
]
推荐阅读
- javascript - Use value from form to render specific data from firebase
- python - 检查td标签python中是否存在href
- xamarin - Toast 通知在 Xamarin UWP Windows 应用程序中不起作用
- go - 为多个端点设置 http 客户端?
- c# - 通过C# Winform向STM32发送UDP数据
- typescript - 绘制多条路径时 react-native-canvas 的性能优化
- angular - 输入类型编号步骤验证 - 自定义表单验证
- mysql - 动态创建表并将数据从 MySQL 复制到 SQL Server 数据库
- sql - 'CASE' 表达式是否将 WHERE 条件应用于查询
- python - 如何按文件名重新组织大量文件?