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]
			});
		}
        }
      }
    }
})
})
相关推荐
JinSo4 小时前
我的2025年度总结:EasyEditor
前端·程序员
喝拿铁写前端8 小时前
前端开发者使用 AI 的能力层级——从表面使用到工程化能力的真正分水岭
前端·人工智能·程序员
wuhen_n8 小时前
LeetCode -- 15. 三数之和(中等)
前端·javascript·算法·leetcode
七月shi人9 小时前
AI浪潮下,前端路在何方
前端·人工智能·ai编程
非凡ghost9 小时前
MusicPlayer2(本地音乐播放器)
前端·windows·学习·软件需求
脾气有点小暴9 小时前
scroll-view分页加载
前端·javascript·uni-app
beckyye9 小时前
ant design vue Table根据数据合并单元格
前端·antd
布列瑟农的星空9 小时前
还在手动翻译国际化词条?AST解析+AI翻译实现一键替换
前端·后端·ai编程
土豆125010 小时前
Rust 错误处理完全指南:从入门到精通
前端·rust·编程语言