zoukankan      html  css  js  c++  java
  • electron用默认浏览器打开链接的3种实现方式

    在使用electron开发桌面程序的过程中,我们可能经常需要让electron程序中包含的链接在被点击后直接调用系统的默认浏览器打开,仔细看了文档的都知道其核心原理就是通过electron的shell模块中的openExternal方法来调用系统默认浏览器打开链接,但是对于其实现又有不同的方法,彻底的接管,选择性的接管,瞎 main介绍3中行之有效的方法。

    1、在渲染进程中选择所有的a标签,覆盖a标签的默认点击方法,代码如下:

    const { shell } = require('electron');
      
    const links = document.querySelectorAll('a[href]');
    links.forEach(link => {
        link.addEventListener('click', e => {
            const url = link.getAttribute('href');
            e.preventDefault();
            shell.openExternal(url);
        });
    });
    

    这种方法的优点是可以精确控制,比如我们可以控制部分链接用系统浏览器打开,部分链接在electron直接打开,缺点就是这个方式只能接管自己可以维护的网页,不能更改第三方网页中链接的打开方式。

    2、该方法与上一种方法类似,只不过换了一种角度来实现,这里打开连接并不在渲染进程中直接做,而是通过和主进程通信来告诉主进程调用系统浏览器打开链接,具体代码如下:

    主进程代码:

    const { app, BrowserWindow, shell, ipcMain } = require('electron');
      
    ...
    ipcMain.on('open-url', (event, url) => {
        shell.openExternal(url);
    });
    ...
    

    渲染进程代码:

    const { shell, ipcRender } = require('electron');
      
    const links = document.querySelectorAll('a[href]');
    links.forEach(link => {
        link.addEventListener('click', e => {
            const url = link.getAttribute('href');
            e.preventDefault();
            ipcRender.send('open-url', url);
        });
    });
    

    上面说了这种方法和上一种方法实现的切入点不太一样,所以和上面的方法有一样的优缺点,对于第三方网站或者iframe中的链接就力所不能及了,那么如何让iframe中的链接也能直接调用系统默认浏览器打开呢?这就是我们要介绍的似3种方式了。

    3、通过在主进程中监听webContents的new-window事件来拦截所有的链接,具体代码:

    const { shell, app } = require('electron');
      
    app.on('web-contents-created', (e, webContents) => {
        webContents.on('new-window', (event, url) => {
            event.preventDefault();
            shell.openExternal(url);
        });
    });
    

    这种方式接管了所有链接的打开方式,优点就是可以处理iframe中或第三方网站链接的打开方式,缺点也很明显,不能单独控制那一类链接通过默认浏览器打开,哪一类链接通过electron直接打开。

    以上3种方法都能在electron中实现调用默认浏览器打开链接,但都葛优优缺点,实际开发中可以根据需求来选择合适的方法。

    来自:https://www.deanhan.cn/electron-url-open-in-default-browser.html

  • 相关阅读:
    Windows远程桌面跳板机无法复制粘贴
    无法打开“XXXX”,因为Apple无法检查其是否包含恶意软件。怎么解决?
    mac下的快捷键
    python:递归函数
    ps:新建Photoshop图像
    python-函数的参数
    python3-定义函数
    python3-调用函数
    python3-函数
    ps:界面概览
  • 原文地址:https://www.cnblogs.com/sxdjy/p/13050322.html
Copyright © 2011-2022 走看看