chrome浏览器插件V3新api---scripting使用方法(个人认为会常用的)
微wx笑
2023-04-13【前端开发】
2
0关键字:
chrome浏览器插件 scripting
在manifest.json里注册权限[scripting,tabs] 1.联合[tabs]api向指定页面中注入js文件 示例(使用场景背景页) //获取当前窗口所有的tab页面 chrome.tabs.query({ cu
在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'],
});转自:https://blog.csdn.net/qq_44450349/article/details/121536935
本文为转载文章,版权归原作者所有,不代表本站立场和观点。



