谷歌插件V3知识点

1.background.js与content.js与popup.js对比:
background.js

生命周期:一开始就执行,最早执行且一直执行;

作用:放置全局的、需要一直运行的代码,权限非常高几乎调用所有Chrome api,还可以发起跨域请求;

 content.js

生命周期:注入页面,在刷新当前页面,或者打开新的tab页执行;

作用范围:可以修改页面DOM,js与目标页面隔壁但是css没有;

 popup.js

生命周期:打开 popup 界面执行,关闭结束;

2.mainfest.json示例:

详细可以参考前端 - Chrome 浏览器插件 V3 版本 Manifest.json 文件全字段解析 - 日升_rs - SegmentFault 思否

{
  "name": "Chrome插件V3",
  "version": "1.0",
  "description": "V3版本",
  // Chrome Extension 版本号,3表示MV3
  "manifest_version": 3,
  // background script配置(根目录为最终build生成的插件包目录)
  "background": {
    "service_worker": "background.js"  可以跨域请求
  },
  // content script配置
  "content_scripts": [
    {
       应用于哪些页面地址(可以使用正则,<all_urls>表示匹配所有地址)
      "matches": ["<all_urls>"], 目标页面
       注入到目标页面的css,注意不要污染目标页面的样式
      "css": ["content.css"],
       注入到目标页面js,这个js是在沙盒里运行,与目标页面是隔离的,没有污染问题。
      "js": ["content.js"],
       代码注入的时机,可选document_start、document_end、document_idle(默认)
      "run_at": "document_end"
    }
  ],
  // 申请chrome extension API权限
  "permissions": ["storage","declarativeContent"],
  // 插件涉及的外部请求地址,暂未发现影响跨域请求,猜测是用于上架商店时方便审核人员查阅
  "host_permissions":[],
  // 如果向目标页面插入图片或者js,需要在这里授权插件本地资源(以下仅为示例)。
  "web_accessible_resources": [
    {
      "resources": [ "/images/app.png" ],
      "matches": ["<all_urls>"]
    },
    {
      "resources": [ "insert.js" ],
      "matches": ["<all_urls>"]
    }
  ],
  // popup页面配置
  "action": {
    // popup页面的路径(根目录为最终build生成的插件包目录)
    "default_popup": "index.html",
    // 浏览器插件按钮的图标
    "default_icon": {
      "16": "/images/app.png",
      "32": "/images/app.png",
      "48": "/images/app.png",
      "128": "/images/app.png"
    },
    // 浏览器插件按钮hover显示的文字
    "default_title": "Vue CRX MV3"
  },
  // 插件图标,图省事的话,所有尺寸都用一个图也行
  "icons": {
    "16": "/images/app.png",
    "32": "/images/app.png",
    "48": "/images/app.png",
    "128": "/images/app.png"
  }
}
 3.chrome.scripting.executeScript(注入js)
当前页面:

需要两个参数:一个为页面id,另一个为要执行的js;

需要在mainfest.json里面配置

"permissions": [

        "activeTab","tabs","scripting"

    ],

第一种: chrome.scripting.executeScript({
                target: { tabId: tab.id },
                func: 函数名,
                 });

第二种: chrome.scripting.executeScript({
                target: { tabId: tab.id },
                files: ['js/options.js'],
                 });

 这里是设置插入当前页面

document.addEventListener('DOMContentLoaded', async function () { 
     console.log('DOMContentLoaded');
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    await chrome.scripting.executeScript({
    target: { tabId: tab.id },
    func: text
    });
})

function text() {
     console.log('改变滤镜');
     document.documentElement.style.filter = "hue-rotate(180deg)"
}

指定页面:
 //获取当前窗口所有的tab页面
  chrome.tabs.query({
    currentWindow: true
  }, function (tabs) {
    //console.log(tabs)
    tabs.forEach(element => {
      //遍历所有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")
iframe页面:
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'],
    });
4. chrome.scripting.insertCSS(注入css)
向当前页面注入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,
    });
})
5.popup.js
在popop.js里面获取popup.html的元素,要放在DOMContentLoaded里面
document.addEventListener('DOMContentLoaded', async function () { 
     const myButton = document.getElementById('changeFilterBtn');  
     console.log('DOMContentLoaded');
    if (myButton) {  
        // 你可以在这里添加事件监听器或其他操作  
        myButton.addEventListener('click', async function() { 
          获取当前活动页面 
               const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
                    await chrome.scripting.executeScript({
                   target: { tabId: tab.id },
                 func: 函数
                      });
        });  
    }

}) 


popup.html

<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8">
    <title>更改当前网页滤镜</title>
    <link rel="stylesheet" href="popup.css">
  </head>

  <body>
    <h1>更改当前网页滤镜</h1>
    <div class="box">
      <button id="changeFilterBtn">更改滤镜</button>
      <button id="resetFilterBtn">去除滤镜</button>
    </div>
    <script src="popup.js"></script>
  </body>

</html>
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值