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   {
				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]
			});
		}
        }
      }
    }
})
})
本站无任何商业行为
个人在线分享 » Chrome plugin插件开发安装之后,不刷新页面也可以使用解决
E-->