6

chrome extension v3 示例(vite)

 2 years ago
source link: https://segmentfault.com/a/1190000041213257
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

项目中使用的chrome extensionv2版本的,不支持一些新特性,比如方法的promise化。

同时希望对框架进行整体的升级,以储备踩坑经验

基于之前的开发痛点,希望新的项目如下

background | popup | content | page 4方同时支持:

  • 互通能力,并支持promise

首先找到了个库

可惜2个库都无法启动我们的项目,可能是因为manifest v3本身也在快速迭代中,甚至在我开发的短短时间内,mv3就支持了popupscript module特性。因此插件开发者跟不上chrome的api更新速度非常正常。

要做的事情

不过插件的思路是可以借鉴的,对我比较重要的地方是:

background | popup | content | page 分别进行打包。但是vite暂时不支持项目中不同文件多种打包方式,所以利用rollup-plugin来达到目的。

对于我们的项目,需要对不支持script module的模块儿content | page采用iife打包模式

const outputs = (await build.generate({ format: "iife" })).output;

bridge

由于background | popup | content | page是互相隔离的,因此想对获取对方数据或者通知对方需要借助chrome.runtime模块儿。但是这种模块儿不支持返回值,因此我们对这个模块儿进行了封装,能够支持4方通信,用法大概如下

// content.js
import api from '@/utils/api';
api.onMessage('server:fetch-iframe-src', async ({ data, sender }: any) => {
    const iframeEl = window.document.querySelector('iframe');
    if (iframeEl) {
      const src = iframeEl.src;
      const urlObj = new URL(src);
      return { src, host: urlObj.hostname };
    }
    
    return null;
});

// popup.html
import api from '@/utils/api';
const { data } = await api.sendTabMessage('server:fetch-iframe-src') as any;
const iframeHost = data.data?.host;

也有可能后面随着mv3的迭代,能够进一步简化vite的配置,未来可期。

由于本文主要是解决方案,没有什么原理性内容,因此大家还是直接看代码吧,各取所需。

https://github.com/defghy/dem...


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK