在manifest.json里注册权限[scripting,tabs]
1.联合[tabs]api向指定页面中注入js文件
示例(使用场景背景页)
//获取当前窗口所有的tab页面
chrome.tabs.query({
currentWindow: true
}, function (tabs) {
//console.log(tabs)
tabs.forEach(element => {
//console.log(element.url)
//遍历所有tab判断网址
if (element.url.includes("www.baidu.com")) {
chrome.tabs.update(element.id, {
active: true
}, function () {
//向指定网址注入js代码
chrome.scripting.executeScript({
target: { tabId: element.id },
files: ['js/options.js'],
});
})
}
});
})
//options.js
alert("我是被注入的js")
2.向页面注入函数
chrome.scripting.executeScript({
target: { tabId: tabId },
func: text
});
//注入页面执行的函数
function text() {
alert("我是测试js代码")
}
3.向当前页面注入css
const css = 'body { background-color: red; }';
chrome.tabs.query({
currentWindow: true,
active: true
}, function (tabs) {
console.log(tabs[0].id)
chrome.scripting.insertCSS({
target: { tabId: tabs[0].id },
css: css,
});
})
注意事项
1.在使用scripting时注意需要等页面加载完再注入
2.使用函数注入方法时,注入的函数无法接收全局变量,应该使用args参数定义一下变量
const color ="red"
function changeBackgroundColor(backgroundColor) {
document.body.style.backgroundColor=backgroundColor;
}
chrome.scripting.executeScript({
target: {tabId: tabId},
func: changeBackgroundColor,
args: [color],
});
3.如果想要在iframe页面也执行的话需要增加:allFrames: true
chrome.scripting.executeScript({
target: {tabId: tabId, allFrames: true},
files: ['script.js'],
});
//指定iframeID执行
const frameIds = [frameId1, frameId2];
chrome.scripting.executeScript({
target: {tabId: tabId, frameIds: frameIds},
files: ['script.js'],
});