chrome浏览器插件V3新api---scripting使用方法(个人认为会常用的)

在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'],
    });

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值