Chrome plugin插件开发安装之后,不刷新页面也可以使用解决

在chrome插件商店安装新的extension时,要想使用这个extension,有些需要刷新一下页面,有些则不需要刷新页面。那么那些不刷新页面的是怎么做到的呢?

chrome extension

做过chrome extension开发都知道,chrome extension文件有background.js、content.js等,当我们执行插件的时候,会发现页面会出现content.js、content.css等文件的注入。因此,只有把content下的文件注入现有的页面中即可。

代码如下:

注意:【scripting】权限

// 监听 插件 安装成功 事件
chrome.runtime.onInstalled.addListener((object) => {
// 获取当前所有窗口
chrome.windows.getAll({ populate: true }, (windows) => {
 
    let currentWindow;
    const w = windows.length;
    for (let i = 0; i < w; i++) {
      currentWindow = windows[i];
      let tab;
      const t = currentWindow.tabs.length;
      for (let j = 0; j < t; j++) {
        tab = currentWindow.tabs[j];
        if (
          !currentTab.url.includes('chrome://') &&
          !currentTab.url.includes('chrome-extension://') &&
          !currentTab.url.includes('chrome.google.com')
        ) {
          //  通过  chrome.scripting 注入
  const scripts = manifest.content_scripts[0].js;
    const s = scripts.length;
    for (let i = 0; i < s; i++) {
      chrome.scripting.executeScript({
        target: { tabId: tab.id },
        files: [scripts[i]]
      });
		}
		const cssFiles = [...(manifest.content_scripts[0].css)];
		try {
			manifest.web_accessible_resources.forEach((item) =>  {
				cssFiles.push(...(item.resources.filter( p => /^content.*\.css$/.test(p))));
			});
		} catch (error) {
			console.log(error);
		}
		if (cssFiles && cssFiles.length) {
			chrome.scripting.insertCSS({
				target: { tabId: tab.id },
				files: [...cssFiles]
			});
		}
        }
      }
    }
})
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

今天也想MK代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值