Author: OBKoro1

Elelctron provides a way to automatically evoke the electron application (pictured below), this time let’s learn how to connect to evoke the electron application, and we can use this feature to do something.

1.1 Protocol Arousal Example:

1.2 What is an Agreement

Electron registers the protocol to the protocol list of the system. The protocol is a system-level API and can only be used in the current system. Computers that do not register other protocols cannot identify the protocol.

Electron’s APP module provides methods for handling protocols that allow you to set and cancel protocols to make your application the default.

1.3 Functions of the Agreement

Register a protocol to the system protocol. When a link to the new protocol is opened through another application/browser web page, the browser will detect whether the protocol is in the system protocol, and if it is registered, then invoke the default handler of the protocol (our application).

1.4 registration protocol: app. SetAsDefaultProtocolClient

The protocol needs to be registered after the ready event, as shown below.

// Register a custom protocol
const { app } = require('electron')
const path = require('path')

// Register a custom protocol
function setDefaultProtocol() {
  const agreement = 'electron-playground-code' // Customize the protocol name
  let isSet = false // Check whether the registration is successful

  app.removeAsDefaultProtocolClient(agreement) // Delete custom protocols each time you run them and then re-register them
  // In development mode running Windows requires compatibility
  if (process.env.NODE_ENV === 'development' && process.platform === 'win32') {
    // Set the paths for electron. Exe and app
    isSet = app.setAsDefaultProtocolClient(agreement, process.execPath, [
      path.resolve(process.argv[1]),])}else {
    isSet = app.setAsDefaultProtocolClient(agreement)
  }
  console.log('Registered successfully', isSet)
}

setDefaultProtocol()
Copy the code

1.5 Protocol

Usage: Enter the registered protocol in the browser address bar to invoke the application.

The format of the link invoked by the protocol: from the protocol name :// parameters

For example, the “electron playground-code” protocol will be triggered with :// by default.

To use it, enter the following information in the browser address bar:

electron-playground-code://1234 //1234 Yes Parameters can be modified based on services
Copy the code

1.6 GIF example of registering the protocol and invoking the background application through the browser:

1.7 The listening application is aroused

The MAC system triggers an open-URL event and the Window system triggers a second-instance event.

// Register a custom protocol
const { app, dialog } = require('electron')
const agreement = 'electron-playground-code' // Customize the protocol name
// Verify that the link is a custom protocol
const AGREEMENT_REGEXP = new RegExp(` ^${agreement}: / / `)

// Listen for custom protocol arousal
function watchProtocol() {
  // MAC wake up will activate open-URL event in open-URL to determine whether to open event for custom protocol
  app.on('open-url'.(event, url) = > {
    const isProtocol = AGREEMENT_REGEXP.test(url)
    if (isProtocol) {
      console.log('Get protocol links, do all sorts of things based on parameters')
      dialog.showMessageBox({
        type: 'info'.message: 'Mac Protocol Custom Protocol Enabled '.detail: 'Custom protocol link:${url}`,})}})// Waking up the application on Windows will activate the second-instance event, which will not be heard until ready
  app.on('second-instance'.(event, commandLine) = > {
    CommandLine is an array in which the awakened link is placed as an element of the array
    commandLine.forEach(str= > {
      if (AGREEMENT_REGEXP.test(str)) {
        console.log('Get protocol links, do all sorts of things based on parameters')
        dialog.showMessageBox({
          type: 'info'.message: 'Window Protocol Custom Protocol enabled'.detail: 'Custom protocol link:${str}`,})}})})}// Listen for custom protocol arousal in the ready event callback
watchProtocol()
console.log('Listening successful')
Copy the code

1.8 Example of invoking an application to execute a callback

1.9 Application Scenarios

  1. To wake up an application, you only need to register the protocol. The system automatically starts the application. Presentation: If the application is not open, the application will be opened; if the application is open, the application window will be activated.
  2. Perform various operations according to the parameters of the protocol link as shown in the above popup window. When the listening protocol link is opened, the complete protocol link can be obtained. We can follow protocol links to perform various business operations. For example, jump to specify the link address, for example, determine whether to log in and then jump, for example, download the specified file, etc.

1.10 Some other apis

App. RemoveAsDefaultProtocolClient (protocol) delete the registration agreement, Boolean return whether deleted successfully

Mac: app. IsDefaultProtocolClient (protocol) whether the current program for the protocol handler.

App. GetApplicationNameForProtocol (url) to obtain the application handler for a link to the agreement

Parameter Description:

Protocol Does not contain :// Registered protocol name.

The url contains: / /

// Other apis related to custom protocols
const { app } = require('electron')
const agreement = 'electron-playground-code' // Customize the protocol name

console.log('Annotate yourself, experiment freely')
const isApp = app.isDefaultProtocolClient(agreement)
console.log('Whether the current program is a custom protocol handler:', isApp)

const AgreementAppName = app.getApplicationNameForProtocol(`${agreement}: / / `)
console.log('Name of the application handler to which this custom protocol link is obtained', AgreementAppName)

const isDelete = app.removeAsDefaultProtocolClient(agreement)
console.log('Delete custom protocol', isDelete)
Copy the code

2. Customize a protocol

To register a user-defined protocol, intercept requests based on existing protocols and return data of the corresponding type according to the registered user-defined protocol type.

We can use all of them automatically

The code address in this project is: electron-playground/app/protocol. You can run the project debug to see the effect.

2.1 protocol. RegisterSchemesAsPrivileged

The protocol is registered as a standard Scheme for subsequent invocation.

Note: It must be called before the Ready event loads and can only be called once.

protocol.registerSchemesAsPrivileged([
  { scheme: 'myscheme'.privileges: { bypassCSP: true}},])Copy the code

2.2 protocol. RegisterFileProtocol

Intercepts the custom protocol request callback and requests the path again after reprocessing.

The sample

protocol.registerFileProtocol(
  'myscheme'.(request, callback) = > {
    // Concatenate absolute path urls
    const resolvePath = path.resolve(__dirname, '.. /.. /playground')
    let url = request.url.replace( `${myScheme}: / / `.' ' )
    url = `${resolvePath}/${url}`
    return callback({ path: decodeURIComponent(url) })
  },
  error= > {
    if (error) console.error('Failed to register protocol')},Copy the code

PS: There are different kinds of loading apis available on the document, and only one of them is demonstrated here.

2.3 Usage Mode

Request files in HTML using a custom protocol, can be automatically intercepted.

The use of address of the project: electron – playground/playground/page/protocol/protocol. The md

<img src={"myscheme://page/protocol/wakeUp.jpg"} alt="wakeUp"/>
Copy the code

2.4 protocol Other apis

protocol.unregisterProtocol(scheme) // Unregister the custom scheme
protocol.isProtocolRegistered(scheme) // Whether a custom protocol has been blocked
protocol.uninterceptProtocol(scheme) // Remove interceptors for custom protocols
// All interceptors are replaced with new interceptors
protocol.interceptFileProtocol(scheme, handler)
protocol.interceptStringProtocol(scheme, handler)
protocol.interceptBufferProtocol(scheme, handler)
protocol.interceptHttpProtocol(scheme, handler)
protocol.interceptStreamProtocol(scheme, handler)
Copy the code

In order to learn electron better, we have created a series at present, if you are interested, you can have a look

  • [Electron playground series] Menu
  • 【Electron Playground series 】Dialog with file selection
  • [Electron playground series] Agreement
  • 【Electron Playground series 】 The tray

For more complete documentation, please refer to the documentation below

Electron-Playground official document

Github address portal: github.com/tal-tech/el…