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]
			});
		}
        }
      }
    }
})
})
相关推荐
IT_陈寒5 分钟前
Redis 性能翻倍的 7 个冷门技巧,第 5 个大多数人都不知道!
前端·人工智能·后端
mCell7 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip7 小时前
Node.js 子进程:child_process
前端·javascript
excel10 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel11 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼13 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping13 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙14 小时前
[译] Composition in CSS
前端·css
白水清风14 小时前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix14 小时前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts