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]
			});
		}
        }
      }
    }
})
})
相关推荐
Hilaku1 小时前
为什么我在团队里禁止使用 axios?
前端·javascript·程序员
兮动人1 小时前
Chrome 152 升级后本地请求全挂了?是 LNA 策略在搞事
前端·chrome·lna·local network
一只游鱼1 小时前
我用原生 JS 做了一个「会呼吸」的博客:Canvas 水境 + 合成音效 + 会破裂的留言气泡(vibe coding)
javascript·agent·canvas·github pages
JarvanMo1 小时前
让 3D 在 Flutter 中焕发生机:Flutter GPU 与 flutter_scene 实战经验
前端
狂师2 小时前
太强了!GitHub上开源了一款AI自动化测试框架,0代码搞定前后端测试!
前端·后端·测试
只睡四小时2 小时前
Local-First 数据契约:一张表装下 4 类数据
前端·javascript·架构设计·local-first·数据契约
迅猛龙办公室2 小时前
Python函数实现反转一个只有3位数的整数
开发语言·前端·python
我星期八休息2 小时前
Redis 的原理和使用(2)
前端·数据库·redis·python·mysql·缓存·bootstrap
Java后端的Ai之路2 小时前
19-ReactJS最佳实践
前端·react.js·前端框架
溪语流沙2 小时前
【Web全栈进阶】文件上传与图片展示:早报站的第一张图片
前端·vue.js·python·fastapi