From 2182ed13006ed8970ca434ea744e994d9efb3a50 Mon Sep 17 00:00:00 2001 From: George Xu Date: Thu, 27 May 2021 12:31:49 -0700 Subject: [PATCH 1/6] docs: modernize protocol-handler docs --- .../index.html | 67 ++----------------- .../main.js | 66 ++++++------------ .../renderer.js | 22 +++--- 3 files changed, 35 insertions(+), 120 deletions(-) diff --git a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/index.html b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/index.html index 1c89c4ce49b13..5a49307e8fb3a 100644 --- a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/index.html +++ b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/index.html @@ -10,76 +10,19 @@

Protocol Handler

-

The app module provides methods for handling protocols.

+

The protocol API allows us to register a custom protocol and intercept existing protocol requests.

These methods allow you to set and unset the protocols your app should be the default app for. Similar to when a browser asks to be your default for viewing web pages.

-

Open the full app API documentation(opens in new window) in your browser.

+

Open the full protocol API documentation in your browser.

-
-

You can set your app as the default app to open for a specific protocol. For instance, in this demo we set this app as the default for electron-api-demos://. The demo button above will launch a page in your default browser with a link. Click that link and it will re-launch this app.

-
Packaging
-

This feature will only work on macOS when your app is packaged. It will not work when you're launching it in development from the command-line. When you package your app you'll need to make sure the macOS plist for the app is updated to include the new protocol handler. If you're using electron-packager then you can add the flag --extend-info with a path to the plist you've created. The one for this app is below.

-
Renderer Process
-

-            const {shell} = require('electron')
-            const path = require('path')
-            const protocolHandlerBtn = document.getElementById('protocol-handler')
-            protocolHandlerBtn.addEventListener('click', () => {
-                const pageDirectory = __dirname.replace('app.asar', 'app.asar.unpacked')
-                const pagePath = path.join('file://', pageDirectory, '../../sections/system/protocol-link.html')
-                shell.openExternal(pagePath)
-            })
-          
-
Main Process
-

-            const {app, dialog} = require('electron')
-            const path = require('path')
-
-            if (process.defaultApp) {
-                if (process.argv.length >= 2) {
-                    app.setAsDefaultProtocolClient('electron-api-demos', process.execPath, [path.resolve(process.argv[1])])
-                }
-            } else {
-                app.setAsDefaultProtocolClient('electron-api-demos')
-            }
-
-            app.on('open-url', (event, url) => {
-                dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`)
-            })
-
-          
-
macOS plist
-

-            
-                
-                    
-                        
-                            CFBundleURLTypes
-                            
-                                
-                                    CFBundleURLSchemes
-                                    
-                                        electron-api-demos
-                                    
-                                    CFBundleURLName
-                                    Electron API Demos Protocol
-                                
-                            
-                            ElectronTeamID
-                            VEKTX9H2N7
-                        
-                    
-                
-            
-
+

You can set your app as the default app to open for a specific protocol. For instance, in this demo we set this app as the default for myapp://. The link above will launch a page in your default browser with a link. Click that link and it will re-launch this app.

+
- +

App Default Protocol Demo

+ +

The protocol API allows us to register a custom protocol and intercept existing protocol requests.

+

These methods allow you to set and unset the protocols your app should be the default app for. Similar to when a + browser asks to be your default for viewing web pages.

+ +

Open the full protocol API documentation in your + browser.

+ + ----- + +

Demo

+

+ First: Launch current page in browser + +

+ +

+ Then: Launch the app from a web link! + Click here to launch the app +

+ + ---- + +

You can set your app as the default app to open for a specific protocol. For instance, in this demo we set this app + as the default for electron-fiddle://. The demo button above will launch a page in your default + browser with a link. Click that link and it will re-launch this app.

+ + +

Packaging

+

This feature will only work on macOS when your app is packaged. It will not work when you're launching it in + development from the command-line. When you package your app you'll need to make sure the macOS plist + for the app is updated to include the new protocol handler. If you're using electron-packager then you + can add the flag --extend-info with a path to the plist you've created. The one for this + app is below:

+ +

+

macOS plist
+

+    
+        
+            
+                
+                    CFBundleURLTypes
+                    
+                        
+                            CFBundleURLSchemes
+                            
+                                electron-api-demos
+                            
+                            CFBundleURLName
+                            Electron API Demos Protocol
+                        
+                    
+                    ElectronTeamID
+                    VEKTX9H2N7
+                
+            
+        
+    
+

+ + + - - - + \ No newline at end of file diff --git a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/main.js b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/main.js index a3a084b38a4e7..91fa304e6a867 100644 --- a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/main.js +++ b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/main.js @@ -1,10 +1,14 @@ // Modules to control application life and create native browser window -const {app, protocol, BrowserWindow, BrowserView} = require('electron') +const { app, BrowserWindow, ipcMain, shell } = require('electron') const path = require('path') -protocol.registerSchemesAsPrivileged([ - { scheme: 'myapp', privileges: { standard: true } } -]) +if (process.defaultApp) { + if (process.argv.length >= 2) { + app.setAsDefaultProtocolClient('electron-fiddle', process.execPath, [path.resolve(process.argv[1])]) + } +} else { + app.setAsDefaultProtocolClient('electron-fiddle') +} function createWindow () { // Create the browser window. @@ -12,32 +16,34 @@ function createWindow () { width: 800, height: 600, webPreferences: { - preload: path.join(__dirname, 'preload.js') + preload: path.join(__dirname, 'preload.js'), } }) - // and load the index.html of the app. mainWindow.loadFile('index.html') } +// Quit when all windows are closed, except on macOS. There, it's common +// for applications and their menu bar to stay active until the user quits +// explicitly with Cmd + Q. +app.on('window-all-closed', function () { + if (process.platform !== 'darwin') app.quit() +}) + // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.whenReady().then(() => { - protocol.registerStringProtocol('myapp', (request, response) => { - response('

hello from myapp://

') - }) + mainWindow = createWindow() +}) - createWindow() - - app.on('activate', function () { - if (BrowserWindow.getAllWindows().length === 0) createWindow() - }) +app.on('open-url', (event, url) => { + dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`) }) -// Quit when all windows are closed, except on macOS. There, it's common -// for applications and their menu bar to stay active until the user quits -// explicitly with Cmd + Q. -app.on('window-all-closed', function () { - if (process.platform !== 'darwin') app.quit() +// Handle window controls via IPC +ipcMain.on('shell:open', (ipcEvent) => { + const pageDirectory = __dirname.replace('app.asar', 'app.asar.unpacked') + const pagePath = path.join('file://', pageDirectory, 'index.html') + shell.openExternal(pagePath) }) diff --git a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/preload.js b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/preload.js new file mode 100644 index 0000000000000..0819c1715786f --- /dev/null +++ b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/preload.js @@ -0,0 +1,12 @@ +// All of the Node.js APIs are available in the preload process. +// It has the same sandbox as a Chrome extension. +const { contextBridge, ipcRenderer } = require('electron') + +// Set up context bridge between the renderer process and the main process +contextBridge.exposeInMainWorld( + 'shell', + { + open: () => ipcRenderer.send('shell:open'), + close: () => ipcRenderer.send('shell:close'), + } +) \ No newline at end of file diff --git a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/renderer.js b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/renderer.js index c2ff9c169717d..525f25ff2e76e 100644 --- a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/renderer.js +++ b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/renderer.js @@ -1,12 +1,8 @@ -// All of the Node.js APIs are available in the preload process. -// It has the same sandbox as a Chrome extension. -window.addEventListener('DOMContentLoaded', () => { - const replaceText = (selector, text) => { - const element = document.getElementById(selector) - if (element) element.innerText = text - } +// This file is required by the index.html file and will +// be executed in the renderer process for that window. +// All APIs exposed by the context bridge are available here. - for (const type of ['chrome', 'node', 'electron']) { - replaceText(`${type}-version`, process.versions[type]) - } -}) +// Binds the buttons to the context bridge API. +document.getElementById('open-in-browser').addEventListener('click', () => { + shell.open(); +}); \ No newline at end of file From 08c2c67e9eba912d0e904cef62887f9ea8187a3c Mon Sep 17 00:00:00 2001 From: George Xu Date: Fri, 28 May 2021 16:50:22 -0700 Subject: [PATCH 3/6] docs: add guide for launch-app-from-URL-in-other-app --- .../main.js | 38 ++-- .../launch-app-from-url-in-another-app.md | 172 ++++++++++++++++++ 2 files changed, 198 insertions(+), 12 deletions(-) create mode 100644 docs/tutorial/launch-app-from-url-in-another-app.md diff --git a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/main.js b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/main.js index 91fa304e6a867..005cac8a1e2b8 100644 --- a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/main.js +++ b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/main.js @@ -2,6 +2,8 @@ const { app, BrowserWindow, ipcMain, shell } = require('electron') const path = require('path') +let mainWindow; + if (process.defaultApp) { if (process.argv.length >= 2) { app.setAsDefaultProtocolClient('electron-fiddle', process.execPath, [path.resolve(process.argv[1])]) @@ -10,9 +12,32 @@ if (process.defaultApp) { app.setAsDefaultProtocolClient('electron-fiddle') } +const gotTheLock = app.requestSingleInstanceLock() + +if (!gotTheLock) { + app.quit() +} else { + app.on('second-instance', (event, commandLine, workingDirectory) => { + // Someone tried to run a second instance, we should focus our window. + if (mainWindow) { + if (mainWindow.isMinimized()) mainWindow.restore() + mainWindow.focus() + } + }) + + // Create mainWindow, load the rest of the app, etc... + app.whenReady().then(() => { + createWindow() + }) + + app.on('open-url', (event, url) => { + dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`) + }) +} + function createWindow () { // Create the browser window. - const mainWindow = new BrowserWindow({ + mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { @@ -30,17 +55,6 @@ app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) -// This method will be called when Electron has finished -// initialization and is ready to create browser windows. -// Some APIs can only be used after this event occurs. -app.whenReady().then(() => { - mainWindow = createWindow() -}) - -app.on('open-url', (event, url) => { - dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`) -}) - // Handle window controls via IPC ipcMain.on('shell:open', (ipcEvent) => { const pageDirectory = __dirname.replace('app.asar', 'app.asar.unpacked') diff --git a/docs/tutorial/launch-app-from-url-in-another-app.md b/docs/tutorial/launch-app-from-url-in-another-app.md new file mode 100644 index 0000000000000..d8ee7a4e78244 --- /dev/null +++ b/docs/tutorial/launch-app-from-url-in-another-app.md @@ -0,0 +1,172 @@ +--- +title: launch-app-from-URL-in-another-app +description: This guide will take you through the process of setting your electron app as the default handler for a specific protocol. +slug: launch-app-from-url-in-another-app +hide_title: true +--- + +# launch-app-from-URL-in-another-app + +## Overview + + + +This guide will take you through the process of setting your electron app as the default handler for a specific [protocol](https://www.electronjs.org/docs/api/protocol). + +By the end of this tutorial, we will have set our app to intercept and handle any clicked URLs that start with a specific protocol. In this guide, the protocol we will use will be "`electron-fiddle://`". + +## Examples + +### Main Process (main.js) + +First we will import the required modules from `electron`. These modules help control our application life and create a native browser window. + +```js +const { app, BrowserWindow, shell } = require('electron') +const path = require('path') +``` + +Next, we will proceed to register our application to handle all "`electron-fiddle://`" protocols. + +```js +if (process.defaultApp) { + if (process.argv.length >= 2) { + app.setAsDefaultProtocolClient('electron-fiddle', process.execPath, [path.resolve(process.argv[1])]) + } +} else { + app.setAsDefaultProtocolClient('electron-fiddle') +} +``` + +We will now define the function in charge of creating our browser window and load our application's `index.html` file. + +```js +function createWindow () { + // Create the browser window. + mainWindow = new BrowserWindow({ + width: 800, + height: 600, + webPreferences: { + preload: path.join(__dirname, 'preload.js') + } + }) + + mainWindow.loadFile('index.html') +} +``` + +In this next step, we will create our `BrowserWindow` and tell our application how to handle an event in which an external protocol is clicked. + +This code will be different in WindowsOS compared to MacOS and Linux. This is due to Windows requiring additional code in order to open the contents of the protocol link within the same electron instance. Read more about this [here](https://www.electronjs.org/docs/api/app#apprequestsingleinstancelock). + +### Windows code: + +```js +const gotTheLock = app.requestSingleInstanceLock() + +if (!gotTheLock) { + app.quit() +} else { + app.on('second-instance', (event, commandLine, workingDirectory) => { + // Someone tried to run a second instance, we should focus our window. + if (mainWindow) { + if (mainWindow.isMinimized()) mainWindow.restore() + mainWindow.focus() + } + }) + + // Create mainWindow, load the rest of the app, etc... + app.whenReady().then(() => { + createWindow() + }) + + // handling the protocol. In this case, we choose to show an Error Box. + app.on('open-url', (event, url) => { + dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`) + }) +} +``` + +### MacOS and Linux code: + +```js +// This method will be called when Electron has finished +// initialization and is ready to create browser windows. +// Some APIs can only be used after this event occurs. +app.whenReady().then(() => { + createWindow() +}) + +// handling the protocol. In this case, we choose to show an Error Box. +app.on('open-url', (event, url) => { + dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`) +}) +``` + +Finally, we will add some additional code to handle when someone closes our application + +```js +// Quit when all windows are closed, except on macOS. There, it's common +// for applications and their menu bar to stay active until the user quits +// explicitly with Cmd + Q. +app.on('window-all-closed', function () { + if (process.platform !== 'darwin') app.quit() +}) +``` + +## Important Note: + +### Packaging + +This feature will only work on macOS when your app is packaged. It will not work when you're launching it in development from the command-line. When you package your app you'll need to make sure the macOS `plist` for the app is updated to include the new protocol handler. If you're using [`electron-packager`](https://github.com/electron/electron-packager) then you +can add the flag `--extend-info` with a path to the `plist` you've created. The one for this app is below: + +### Plist + +```XML +

+

macOS plist
+

+    
+        
+            
+                
+                    CFBundleURLTypes
+                    
+                        
+                            CFBundleURLSchemes
+                            
+                                electron-api-demos
+                            
+                            CFBundleURLName
+                            Electron API Demos Protocol
+                        
+                    
+                    ElectronTeamID
+                    VEKTX9H2N7
+                
+            
+        
+    
+

+``` + +## Conclusion + +After you start your electron app, you can now enter in a URL in your browser that contains the custom protocol, for example `"electron-fiddle://open"` and observe that the application will respond and show an error dialog box. + + + +```fiddle docs/fiddles/system/protocol-handler/launch-app-from-url-in-another-app + +``` + + From 8b769b4ebc98b1b24b3b4ea1aa2ad872d9542f38 Mon Sep 17 00:00:00 2001 From: George Xu Date: Mon, 21 Jun 2021 11:20:07 -0700 Subject: [PATCH 4/6] docs: address comments --- .../index.html | 38 +++++++++---------- .../main.js | 4 +- .../preload.js | 1 - .../launch-app-from-url-in-another-app.md | 9 +++-- 4 files changed, 27 insertions(+), 25 deletions(-) diff --git a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/index.html b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/index.html index 732ac0cae8c82..a3ddd1b933fc0 100644 --- a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/index.html +++ b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/index.html @@ -51,25 +51,25 @@

Packaging

macOS plist

-    
-        
-            
-                
-                    CFBundleURLTypes
-                    
-                        
-                            CFBundleURLSchemes
-                            
-                                electron-api-demos
-                            
-                            CFBundleURLName
-                            Electron API Demos Protocol
-                        
-                    
-                    ElectronTeamID
-                    VEKTX9H2N7
-                
-            
+    <?xml version="1.0" encoding="UTF-8"?>
+    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+            <plist version="1.0">
+                <dict>
+                    <key>CFBundleURLTypes</key>
+                    <array>
+                        <dict>
+                            <key>CFBundleURLSchemes</key>
+                            <array>
+                                <string>electron-api-demos</string>
+                            </array>
+                            <key>CFBundleURLName</key>
+                            <string>Electron API Demos Protocol</string>
+                        </dict>
+                    </array>
+                    <key>ElectronTeamID</key>
+                    <string>VEKTX9H2N7</string>
+                </dict>
+            </plist>
         
     

diff --git a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/main.js b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/main.js index 005cac8a1e2b8..0dd559ef397bb 100644 --- a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/main.js +++ b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/main.js @@ -31,7 +31,7 @@ if (!gotTheLock) { }) app.on('open-url', (event, url) => { - dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`) + dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`) }) } @@ -56,7 +56,7 @@ app.on('window-all-closed', function () { }) // Handle window controls via IPC -ipcMain.on('shell:open', (ipcEvent) => { +ipcMain.on('shell:open', () => { const pageDirectory = __dirname.replace('app.asar', 'app.asar.unpacked') const pagePath = path.join('file://', pageDirectory, 'index.html') shell.openExternal(pagePath) diff --git a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/preload.js b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/preload.js index 0819c1715786f..1eebf784ad672 100644 --- a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/preload.js +++ b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/preload.js @@ -7,6 +7,5 @@ contextBridge.exposeInMainWorld( 'shell', { open: () => ipcRenderer.send('shell:open'), - close: () => ipcRenderer.send('shell:close'), } ) \ No newline at end of file diff --git a/docs/tutorial/launch-app-from-url-in-another-app.md b/docs/tutorial/launch-app-from-url-in-another-app.md index d8ee7a4e78244..f8f44e42b21fe 100644 --- a/docs/tutorial/launch-app-from-url-in-another-app.md +++ b/docs/tutorial/launch-app-from-url-in-another-app.md @@ -5,15 +5,18 @@ slug: launch-app-from-url-in-another-app hide_title: true --- -# launch-app-from-URL-in-another-app +# Launching Your Electron App From A URL In Another App ## Overview -This guide will take you through the process of setting your electron app as the default handler for a specific [protocol](https://www.electronjs.org/docs/api/protocol). +This guide will take you through the process of setting your electron app as the default +handler for a specific [protocol](https://www.electronjs.org/docs/api/protocol). -By the end of this tutorial, we will have set our app to intercept and handle any clicked URLs that start with a specific protocol. In this guide, the protocol we will use will be "`electron-fiddle://`". +By the end of this tutorial, we will have set our app to intercept and handle +any clicked URLs that start with a specific protocol. In this guide, the protocol +we will use will be "`electron-fiddle://`". ## Examples From d13703bd7f42d6aaa41aac5102dea9266dfd4cbc Mon Sep 17 00:00:00 2001 From: George Xu Date: Tue, 6 Jul 2021 10:19:54 -0700 Subject: [PATCH 5/6] chore: fix brackets --- .../launch-app-from-URL-in-another-app/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/index.html b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/index.html index a3ddd1b933fc0..aab84bf021675 100644 --- a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/index.html +++ b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/index.html @@ -51,7 +51,7 @@

Packaging

macOS plist

-    <?xml version="1.0" encoding="UTF-8"?>
+    
     <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
             <plist version="1.0">
                 <dict>

From 78798569529efef8b9ed324b3a20729e5be13d1e Mon Sep 17 00:00:00 2001
From: George Xu 
Date: Thu, 8 Jul 2021 11:13:00 -0700
Subject: [PATCH 6/6] chore: add escaped brackets

---
 .../launch-app-from-URL-in-another-app/index.html               | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/index.html b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/index.html
index aab84bf021675..a3ddd1b933fc0 100644
--- a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/index.html
+++ b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/index.html
@@ -51,7 +51,7 @@ 

Packaging

macOS plist

-    
+    <?xml version="1.0" encoding="UTF-8"?>
     <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
             <plist version="1.0">
                 <dict>