首页 > 解决方案 > 无法从 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  

标签: javascriptwebgoogle-chrome-extensionconsoleconsole.log

解决方案


确保在 manifest.json 中设置了 content.js(如果没有 content.css,则省略该 css 行):

"content_scripts": [
    {
      "matches": [ "theurlyouwanttoinjectthecontentscripton" ],
      "js": ["content.js"],
      "css": ["content.css"]
    }
]

推荐阅读