6
头图

File processing-Chrome extension

This article mainly introduces how Electron uses Chrome extensions.
Electron does not support all Chrome extension APIs. Please refer to the supported extension api .
The extended loading must be app.whenReady after 060df056fa8820.

electron-devtools-installer

This library is mainly a package that installs the DevTool extension to Electron, and integrates the DevTool extension of the mainstream front-end library, link .
For example, we want to install the DevTool of vue3:

npm install electron-devtools-installer --save-dev

import installExtension, { VUEJS3_DEVTOOLS } from "electron-devtools-installer"

const { app } = require('electron')

app.whenReady().then(async () => {
  try {
    await installExtension(VUEJS3_DEVTOOLS)
  } catch (e) {
      console.error("Vue Devtools failed to install:", e.toString())
    }
})
// VUEJS3_DEVTOOLS这里传入的拓展id,实际上等同于

await installExtension({
  id: 'ljjemllljcmogpfapbkkighbhhppjdbg', // vue3拓展id
  electron: '>=1.2.1'
})

拓展id

Of course, this method is an extension of installation from the chrome online application store, so if the network cannot connect to the external network, it will basically not be installed.

Local installation extension

Electron provides a method to install the extension locally, you only need to pass in the extension directory (this is the path after the extension is decompressed, not the crx file).

// Electron 9以下
BrowserWindow.addExtension(path)
BrowserWindow.addDevToolsExtension(path)
// Electron 9及以上
session.defaultSession.loadExtension(path)

If we download the extended crx file on the Internet, install this extension on Google Chrome:

  • Under Windows, it is %LOCALAPPDATA%\Google\Chrome\User Data\Default\Extensions
  • Under Linux:

    ~/.config/google-chrome/Default/Extensions/
    ~/.config/google-chrome-beta/Default/Extensions/
    ~/.config/google-chrome-canary/Default/Extensions/
    ~/.config/chromium/Default/Extensions/
  • ~/Library/Application Support/Google/Chrome/Default/Extensions under macOS

For example, mine is located at C:\Users\Administrator\AppData\Local\Google\Chrome\User Data\Default\Extensions , and its extension id is the directory name. For example, vue3 is the ljjemllljcmogpfapbkkighbhhppjdbg directory. We find this directory and copy it out (of course you can also use this path directly) and put it in

win:C:\Users\Administrator(你的用户)\AppData\Roaming\<app name>\extensions
mac:/Users/<user name>/Library/Application Support/<app name>/Extensions(大概,这个没测试)
反正是app.getPath("userData")目录下的extensions目录中

Use the corresponding loading method (this tutorial version is 12, so use session loading):

await session.defaultSession.loadExtension(
  path.join(
    app.getPath("userData"),
    "/extensions/chklaanhfefbnpoihckbnefhakgolnmc/0.0.32.3_0"
  ),
  // 打开本地文件也应用拓展
  { allowFileAccess: true }
)

It should be noted that the path of manifest.json the root directory of the 060df056fa8a45 file, and there is a directory with a version number under the downloaded extension id directory, such as 0.0.32.3_0 above. Please check it yourself. The console will report a warning after the installation is successful, but Does not affect the use, see when the official removal of issues
拓展id

Small demo

We load a json-beautified extension JSONView . The file is put in the same way as above, so I won’t say more.

主进程:
async function onAppReady() {
  if (!process.env.WEBPACK_DEV_SERVER_URL) {
    createProtocol('app')
  }
  if (isDevelopment && !process.env.IS_TEST) {
    try {
      await session.defaultSession.loadExtension(
        path.join(
        app.getPath('userData'),
            '/extensions/chklaanhfefbnpoihckbnefhakgolnmc/0.0.32.3_0'
           ),
           { allowFileAccess: true }
        )
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
    initWindow()
  }
}

渲染进程:
<template>
  <div class="extensions">
    <a-upload
      accept="application/json"
      :customRequest="customRequest"
      name="file"
      :showUploadList="false"
      :multiple="true"
    >
      <a-button>
        <upload-outlined></upload-outlined>
        打开json
      </a-button>
    </a-upload>
  </div>
</template>

<script>
const { remote } = require('electron')
import { defineComponent, getCurrentInstance } from 'vue'

export default defineComponent({
  setup() {
    const { proxy } = getCurrentInstance()
    const { $message } = proxy
    function customRequest(fileData) {
      const path = fileData.file.path
      if (remote.session.defaultSession.getExtension('chklaanhfefbnpoihckbnefhakgolnmc')) {
        window.open('file:///' + path)
      } else {
        $message.warning('没有加载json拓展')
      }
    }
    return {
      customRequest
    }
  },
})
</script>

We choose a json file to open, and open the json directly in window.open to see if there is any json beautification effect (note that the file protocol must be used when loading local files and the application extension, otherwise the extension will not take effect).
拓展id

This series of updates can only be organized during weekends and after get off work. If there are more content, the update will be slower. I hope it can be helpful to you. Please support it by star or like favorites.

The address of this article: https://xuxin123.com/electron/chrome-extension
This github address: link


陌路凡歌
7.9k 声望259 粉丝

人笨,多听,多写,多看书