我必须通过Chrome扩展程序在Google搜索页面中添加div 我的inject.js文件如下:
var body=document.getElementById("search");
//creates bar and creates bar removal function
var bar = document.createElement("DIV");
function removeBar(){
bar.remove();
}
//styles bar
var ds = bar.style;
ds.position = "fixed";
ds.width = "512px";
ds.height = "33px";
ds.background = "rgba(0,0,0,0.86)";
ds.zIndex = "9999999999999";
//creates X button and makes it so clicking it runs the removeBar() function
var x = document.createElement("BUTTON");
x.onclick = removeBar;
bar.appendChild(x);
//styles button
var xs = x.style;
xs.background = "black";
xs.borderColor = "black";
xs.color = "rgba(255,255,255,.86)";
xs.position = "fixed";
xs.left = "100%";
xs.marginTop = "5px";
xs.marginLeft = "-29px"
//puts X in button
var xtext = document.createTextNode("X");
x.appendChild(xtext);
//puts bar in page
body.insertBefore(bar, body.children[0]);
我的manifest.json如下:
{
"manifest_version": 2,
"name": "Inject script in webpage",
"version": "2.0.1",
"description": "inject script in webpage.",
"icons": {
"48" : "sample-48.png",
"128" : "sample-128.png"
},
"content_scripts": [
{
"matches": ["https://www.google.com.pk/*"],
"js" : ["inject.js"],
"all_frames": true
}
]
}
但是当我加载google SERP页面时,错误消息显示有点像“无法调用”insertBefore“属性为null”,似乎变量“body”未定义。通过谷歌页面的检查元素我检查了ID为“搜索”的DIV存在,如果我做错了那么plzz让我知道我是chrome扩展开发的新手
答案 0 :(得分:0)
问题可能在这里:
var body=document.getElementById("search");
"身体"变量为空 - 可能是因为您要查找的ID不存在。尝试寻找其他一些id(我用过" gbqfb")。但是,您应该学习使用Chrome的内置调试器来找出您的代码无法正常工作的原因,而不是在这里为您提供答案。看看这个youtube视频: