Developing Chrome Extensions with Svelte

1. Background

Cause After the Chrome browser was upgraded to version 96 recently, the QR code entry was moved from the address bar to the secondary menu. This is not very friendly to H5 front-end development, and every time you need a page QR code, you need to click twice (* ̄︿ ̄).

Therefore, the idea of ​​developing a QR code Chrome Extension was born (@ ̄ー ̄@).

After multiple technical selections (React, native, Vue, Svelte, etc.), I finally chose Svelte because

  • Simple grammar, low mental burden
  • Less runtime code, small package size
  • Responsive

d======( ̄▽ ̄*), then start the journey of Svelte × Chrome Extension.

2. Create & develop

2.1 Project Creation

2.1.1 Project initialization

Use Svelte Kit to create a new project npm`` init svelte@next qrcode-extension with the following directory structure:

  • src: Source file directory

    • lib: component library, etc.
    • routes: Conventional routing file
    • app.html: entry template file
  • static: static files directory
  • svelte.config.js:svelte configuration

It can be started directly after initializing the project npm`` run dev .

2.1.2 Support plug-in development

  1. manifest file

Extensions are built on web technologies such as HTML, JavaScript, and CSS.

- Chrome Dev Documentation

  1. Chrome plug-ins are manifest.jsonessentially a series of front-end resource collections specified for the entry, and implement various functions based on the API provided by the Chrome browser.

So add the file in your project's static resource files directory manifest.json:

{
  "name": "QrCode",
  "description": "A simple qrcode extension powered by Svelte",
  "version": "1.0",
  "manifest_version": 3,
  "permissions": ["tabs", "downloads"],
  "action": {
    "default_popup": "index.html"
  },
  "icons": {
    "16": "/images/qrcode-16.png",
    "32": "/images/qrcode-32.png",
    "48": "/images/qrcode-48.png",
    "128": "/images/qrcode-128.png"
  }
}
复制代码

A few more important fields:

MV3 file format reference

  • manifest_version: Manifest version, previously Manifest V2 (MV2), Chrome recommends Manifest V3 (MV3)
  • permissions:扩展要使用的浏览器权限,大部分Chrome扩展API均有权限依赖
  • action:定义插件操作行为对应的页面

    • default_popup:点击插件图标时的页面
  • icons:插件图标
  1. 添加chrome类型定义
  1. 安装@types/chrome到devDependencies,并在tsconfig.json#compilerOptions#types中添加chrome类型。

2.2 功能开发

2.2.1 需求拆分

  1. 参考Chrome浏览器二维码功能:

2.2.2 链接展示

  1. 需要获取Chrome浏览器当前打开的tab,查阅开发文档可知对应API为chrome.tabs,并在manifest.json#permissions添加tabs权限声明。

在首页加载时,获取当前tab的url,url展示到输入框,并作为二维码组件的输入属性。

async function getCurrentTab() {
  if (typeof chrome === 'undefined' || typeof chrome.tabs === 'undefined') {
    return { url: '' };
  }
  let queryOptions = { active: true, currentWindow: true };
  let [tab] = await chrome.tabs.query(queryOptions);
  return tab;
}

import { onMount } from 'svelte';

let url = '';
// get current tab's url
onMount(() => {
  (async () => {
    const tab = await getCurrentTab();
    url = tab.url || '';
  })();
});
复制代码

2.2.3 Svelte组件

二维码组件代码定义在libs/QrCode.svelte中。

  1. 组件代码

Svelte与vue类似,提供单文件组件。包括三部分:

  • <script></script>:js/ts业务逻辑
  • html:组件html模板
  • <style></style>:css样式,编译时自动做样式隔离

组件详细代码如下所示,使用qrcode库生成二维码。

<script lang="ts">
  import { toDataURL } from 'qrcode';
  import type { QRCodeToDataURLOptions } from 'qrcode';
  import { writable } from 'svelte/store';
  import { createEventDispatcher } from 'svelte';

  // 输入属性
  export let text;
  export let option: QRCodeToDataURLOptions = {
    type: 'image/png',
    margin: 2,
    width: 240
  };

  const dataUrl = writable('');
  const dispatch = createEventDispatcher();
  
  // 响应式
  $: {
    if (text) {
      toDataURL(text, option).then((url) => {
        dataUrl.set(url);
        // 派发组件事件
        dispatch('ready', { url });
      });
    } else {
      dataUrl.set('');
    }
  }
</script>

<div class="qrcode">
{#if $dataUrl}
  <img src={$dataUrl} alt="qrcode">
{/if}
</div>

<style>
  .qrcode {
    width: 240px;
    height: 240px;
    border: 2px solid #e8eaed;
    border-radius: 10px;
    background: #f1f3f4;
  }

  img {
    width: 100%;
    height: auto;
    border-radius: 10px;
  }
</style>
复制代码
  1. 生命周期
  • onMount:组件已挂载到DOM上(SSR时不执行)
  • beforeUpdate:组件状态变更时立即执行,第一次会在onMount之前执行
  • afterUpdate:组件更新后
  • onDestroy:组件卸载(如onMount返回函数,则会执行)

  1. 输入/输出
  1. 组件中通过export声明输入属性。
export let text;
export let option: QRCodeToDataURLOptions = {
  type: 'image/png',
  margin: 2,
  width: 240
};
复制代码
  1. 使用createEventDispatcher创建事件,当生成二维码图片base64时,触发ready事件。
import { createEventDispatcher } from 'svelte';

const dispatch = createEventDispatcher();

dispatch('ready', { url });
复制代码
  1. 响应式
  1. 参考:svelte响应式代码块
  1. 利用label语法声明响应式逻辑,当输入属性text变化时更新二维码内容。
$: {
  if (text) {
    toDataURL(text, option).then((url) => {
      dataUrl.set(url);
      dispatch('ready', { url });
    });
  } else {
    dataUrl.set('');
  }
}
复制代码

2.2.4 二维码下载

下载对应的Chrome API为chrome.downloads,同样在manifest.json#permissions添加downloads权限声明。

监听二维码组件ready事件,并更新dataUrl。点击下载按钮时触发二维码下载。

function downloadQrCode() {
  if (!dataUrl) {
    return;
  }

  chrome.downloads?.download({
    url: dataUrl,
    filename: getFilename(url),
  });
}

<button class="qrcode-download" on:click={downloadQrCode}>下载</button>
复制代码

三、调试&构建

3.1 构建

Before you can deploy your SvelteKit app, you need to adapt it for your deployment target. Adapters are small plugins that take the built app as input and generate output for deployment.

—— Svelte Adapter

Svelte使用adapter转换编译产物,默认提供的adapter是@sveltejs/adapter-auto,需要配置打包目标平台(Vercel、Cloudflare、Netlify)。一般使用@sveltejs/adapter-static打包静态产物。

默认打包路径为build,static文件夹下的静态资源会打包到根路径。

但用Chrome加载这个产物作为插件会报错,

ERROR Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-ri/Klr/GKqsTbCFK6rSYKj7VDIccXQJeipKxBmqg69g='), or a nonce ('nonce-...') is required to enable inline execution.

The reason is that it violates the CSP policy and index.htmluses an inline script script, and this file is dynamically generated during packaging. The unsafe-inline keyword or nonce- and other methods mentioned in the error are not supported in MV3.

Solution After compiling, match all inline scripts in html files, write the content of inline scripts into js files, and replace them with sctipt tags in html files. Customize the adapter to complete the product conversion operation.

import type { Adapter } from '@sveltejs/kit';
import * as glob from 'fast-glob';
import { readFileSync, writeFileSync } from 'fs';
import { dirname, join } from 'path';

interface Props {
  /** dest for extension package dir */   dest: string;
}

function uuid() {
  return Math.random().toString(36).slice(2);
}

function handleHtml(htmlPath, scriptTag) {
  const html = readFileSync(htmlPath).toString();
  const matchReg = /<script\b[^>]*>([\s\S]*)</script>/gm;
  const result = matchReg.exec(html);

  return result && result[1]
    ? {
        html: html.replace(matchReg, scriptTag),
        script: result[1],
      }
    : null;
}

export function extensionAdapter({ dest }: Props): Adapter {
  return {
    name: 'crx-adapter',

    async adapt({ utils }) {
      utils.rimraf(dest);

      utils.copy_static_files(dest);
      utils.copy_client_files(dest);
      utils.rimraf(join(dest, '_app'));

      await utils.prerender({ all: true, dest: dest });

      const fileNames = await glob(join(dest, '**', '*.html'));
      for (const fileName of fileNames) {
        const dir = dirname(fileName);
        const scriptFileName = `start-${uuid()}.js`;
        const res = handleHtml(
          fileName,
          `<script type="module" src="/${scriptFileName}"></script>`,
        );

        if (res) {
          writeFileSync(fileName, res.html);
          writeFileSync(join(dir, scriptFileName), res.script);
        }
      }
    },
  };
}
复制代码

3.2 Debug

After the product is packaged, open the Chrome browser and enter chrome://extensions/

  • Click "Load unpacked extension", select the package directory to load the plugin
  • When the product is updated, rebuild and refresh the plugin

3.3 Effects

The final effect is as follows, click the plug-in button in the webpage, and the corresponding QR code will be displayed.

Compare:

Chrome comes with qrcode-extension

4. Summary

The main work of this paper is as follows:

  • Using Svelte to develop QR code Chrome Extension
  • Customize the Svelte Adapter to adapt to the Chrome plug-in security policy

Guess you like

Origin juejin.im/post/7102391899918434341