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]
			});
		}
        }
      }
    }
})
})
相关推荐
测试界柠檬1 分钟前
面试真题 | web自动化关闭浏览器,quit()和close()的区别
前端·自动化测试·软件测试·功能测试·程序人生·面试·自动化
多多*2 分钟前
OJ在线评测系统 登录页面开发 前端后端联调实现全栈开发
linux·服务器·前端·ubuntu·docker·前端框架
2301_801074152 分钟前
TypeScript异常处理
前端·javascript·typescript
ᅠᅠᅠ@3 分钟前
异常枚举;
开发语言·javascript·ecmascript
小阿飞_3 分钟前
报错合计-1
前端
caperxi5 分钟前
前端开发中的防抖与节流
前端·javascript·html
霸气小男5 分钟前
react + antDesign封装图片预览组件(支持多张图片)
前端·react.js
susu10830189116 分钟前
前端css样式覆盖
前端·css
学习路上的小刘7 分钟前
vue h5 蓝牙连接 webBluetooth API
前端·javascript·vue.js
&白帝&8 分钟前
vue3常用的组件间通信
前端·javascript·vue.js