Electron - 如何在Linux上创建深度链接

3
我有一个 ElectronJS 项目,其中使用了协议(deep-link)。在 MacOS 和 Windows 上工作正常,但在 Linux 上我不知道如何创建此协议。
我已经查阅了 ElectronJS 文档以及网络上的问题等等,但我无法弄清楚如何在 Linux 上初始化协议。我想要实现与应用程序交互的深度链接协议,就像在 MacOS 和Windows 上成功实现一样。
适用于 MacOS 和 Windows 的代码:
// main.ts

// –– B ––– PROTOCOL HANDLER –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

ProtocolUtils.setDefaultProtocolClient();

// eslint-disable-next-line default-case
switch (process.platform) {
    case 'darwin':
        ProtocolUtils.setProtocolHandlerOSX();
        break;
    case 'win32':
        ProtocolUtils.setProtocolHandlerWin32();
        break;
}
// –– E ––– PROTOCOL HANDLER –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––


// protocol.ts

export abstract class ProtocolUtils {
    /**
     * @description Create default protocole for call this app.
     *  Ex : in your browser => myapp://test
     */
    public static setDefaultProtocolClient(): void {
        if (!app.isDefaultProtocolClient('myapp')) {
            // Define custom protocol handler.
            // Deep linking works on packaged versions of the application!
            app.setAsDefaultProtocolClient('myapp');
        }
    }

    /**
     * @description Create logic (WIN32) for open url from protocol
     */
    public static setProtocolHandlerWin32(): void {
        // Force Single Instance Application on win32
        const gotTheLock = app.requestSingleInstanceLock();

        app.on('second-instance', (e: Electron.Event, argv: string[]) => {
            // Someone tried to run a second instance, we should focus our window.
            if (MainWindow.mainWindow) {
                if (MainWindow.mainWindow.isMinimized()) MainWindow.mainWindow.restore();
                MainWindow.mainWindow.focus();
            } else {
                MainWindow.openMainWindow(); // Open main windows
            }

            app.whenReady().then(() => {
                MainWindow.mainWindow.loadURL(this._getDeepLinkUrlForWin32(argv)); // Load URL in WebApp
            });
        });

        if (gotTheLock) {
            app.whenReady().then(() => {
                MainWindow.openMainWindow(); // Open main windows
                MainWindow.mainWindow.loadURL(this._getDeepLinkUrlForWin32()); // Load URL in WebApp
            });
        } else {
            app.quit();
        }
    }

    /**
     * @description Create logic (OSX) for open url from protocol
     */
    public static setProtocolHandlerOSX(): void {
        app.on('open-url', (event: Electron.Event, url: string) => {
            event.preventDefault();
            app.whenReady().then(() => {
                MainWindow.openMainWindow(); // Open main windows
                MainWindow.mainWindow.loadURL(this._getUrlToLoad(url)); // Load URL in WebApp
            });
        });
    }

    /**
     * @description Format url to load in mainWindow
     */
    private static _getUrlToLoad(url: string): string {
        // Ex: url = myapp://deep-link/test?params1=paramValue
        // Ex: Split for remove myapp:// and get deep-link/test?params1=paramValue
        const urlSplitted = url.split('//');
        // Generate URL to load in WebApp.
        // Ex: file://path/index.html#deep-link/test?params1=paramValue
        const urlToLoad = format({
            pathname: Env.BUILDED_WEBAPP_INDEX_PATH,
            protocol: 'file:',
            slashes: true,
            hash: `#${urlSplitted[1]}`,
        });

        return urlToLoad;
    }

    /**
    * @description Resolve deep link url for windows from process argv
    */
    private static _getDeepLinkUrlForWin32(argv?: string[]): string {
        let url: string;
        const newArgv: string[] = !isNil(argv) ? argv : process.argv;
        // Protocol handler for win32
        // argv: An array of the second instance’s (command line / deep linked) arguments
        if (process.platform === 'win32') {
            // Get url form precess.argv
            newArgv.forEach((arg) => {
                if (/myapp:\/\//.test(arg)) {
                    url = arg;
                }
            });

            if (!isNil(url)) {
                return this._getUrlToLoad(url); // Load URL in WebApp
            } else if (!isNil(argv) && isNil(url)) {
                throw new Error('URL is undefined');
            }
        }
    }
}

对于macOS和Windows我没有担心,但在Linux上即使使用ProtocolUtils.setDefaultProtocolClient();,也无法创建myapp: //协议...

当我运行此命令:xdg-open myapp://deep-link/test?toto=titi,会出现一个错误提示我该协议不存在。

如果有人能给我一个在Linux上配置的示例或者帮我解决问题?

谢谢

1个回答

1

好的,我找到了解决方案!

首先,我们删除了electron-forge,并将其替换为electron-builder(参见文档)。

然后,在阅读了大量有关Linux深度链接的文档之后,例如:

我的解决方案是:

# electron-builder.yml
appId: com.myapp.myapp
productName: myapp
directories:
    output: out
linux:
    icon: src/assets/icons/app/icon@256x256.png
    category: Utility
    mimeTypes: [x-scheme-handler/myapp] # Define MimeType
    desktop:                            # Define desktop elem
        exec: myapp %u                  # Define Exec
    target:
        - target: deb
          arch:
              - x64

因此,我在这里使用我的协议名称 myapp 定义了MimeType,这可能会提供以下内容:

myapp://toto?foo=bar

在我的桌面文件中,使用 myapp %u 定义Exec,因为 %u => 单个URL。本地文件可以作为file: URL或文件路径传递。(参见 doc

最后,在我的main.tsprotocol.utils.ts中:

// main.ts


// –– B ––– PROTOCOL HANDLER –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

ProtocolUtils.setDefaultProtocolClient();

switch (process.platform) {
    case 'darwin':
        ProtocolUtils.setProtocolHandlerOSX();
        break;
    case 'linux':
    case 'win32':
        ProtocolUtils.setProtocolHandlerWindowsLinux();
        break;
    default:
        throw new Error('Process platform is undefined');
}
// –– E ––– PROTOCOL HANDLER –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

// protocol.utils.ts

export abstract class ProtocolUtils {
    public static setDefaultProtocolClient(): void {
        if (!app.isDefaultProtocolClient('myapp')) {
            // Define custom protocol handler.
            // Deep linking works on packaged versions of the application!
            app.setAsDefaultProtocolClient('myapp');
        }
    }

    /**
     * @description Create logic (WIN32 and Linux) for open url from protocol
     */
    public static setProtocolHandlerWindowsLinux(): void {
        // Force Single Instance Application
        const gotTheLock = app.requestSingleInstanceLock();

        app.on('second-instance', (e: Electron.Event, argv: string[]) => {
            // Someone tried to run a second instance, we should focus our window.
            if (MainWindow.mainWindow) {
                if (MainWindow.mainWindow.isMinimized()) MainWindow.mainWindow.restore();
                MainWindow.mainWindow.focus();
            } else {
                // Open main windows
                MainWindow.openMainWindow();
            }

            app.whenReady().then(() => {
                MainWindow.mainWindow.loadURL(this._getDeepLinkUrl(argv));
            });
        });

        if (gotTheLock) {
            app.whenReady().then(() => {
                // Open main windows
                MainWindow.openMainWindow();
                MainWindow.mainWindow.loadURL(this._getDeepLinkUrl());
            });
        } else {
            app.quit();
        }
    }

    /**
     * @description Create logic (OSX) for open url from protocol
     */
    public static setProtocolHandlerOSX(): void {
        app.on('open-url', (event: Electron.Event, url: string) => {
            event.preventDefault();
            app.whenReady().then(() => {
                if (!isNil(url)) {
                    // Open main windows
                    MainWindow.openMainWindow();
                    MainWindow.mainWindow.loadURL(this._getUrlToLoad(url));
                } else {
                    this._logInMainWindow({ s: 'URL is undefined', isError: true });
                    throw new Error('URL is undefined');
                }
            });
        });
    }

    /**
     * @description Format url to load in mainWindow
     */
    private static _getUrlToLoad(url: string): string {
        // Ex: url = myapp://deep-link/test?params1=paramValue
        // Ex: Split for remove myapp:// and get deep-link/test?params1=paramValue
        const splittedUrl = url.split('//');
        // Generate URL to load in WebApp.
        // Ex: file://path/index.html#deep-link/test?params1=paramValue
        const urlToLoad = format({
            pathname: Env.BUILDED_APP_INDEX_PATH,
            protocol: 'file:',
            slashes: true,
            hash: `#${splittedUrl[1]}`,
        });

        return urlToLoad;
    }

    /**
    * @description Resolve deep link url for Win32 or Linux from process argv
    * @param argv: An array of the second instance’s (command line / deep linked) arguments
    */
    private static _getDeepLinkUrl(argv?: string[]): string {
        let url: string;
        const newArgv: string[] = !isNil(argv) ? argv : process.argv;
        // Protocol handler
        if (process.platform === 'win32' || process.platform === 'linux') {
            // Get url form precess.argv
            newArgv.forEach((arg) => {
                if (/myapp:\/\//.test(arg)) {
                    url = arg;
                }
            });

            if (!isNil(url)) {
                return this._getUrlToLoad(url);
            } else if (!isNil(argv) && isNil(url)) {
                this._logInMainWindow({ s: 'URL is undefined', isError: true });
                throw new Error('URL is undefined');
            }
        }
    }

而且它工作了 :D


你能分享一下你的MainWindow逻辑吗?我的意思是,你是如何与protocolHandler共享mainwindow的。 - LeoPucciBr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接