Electronでリンククリック時にデフォルトブラウザで開く

electron1

 

Shellモジュールのインポート

const shell = electron.shell;

 

 setWindowOpenHandlerで新しいウィンドウが開かれるときの挙動を定義

 

mainWindow.webContents.setWindowOpenHandler(({ url }) => {
  if (url.startsWith('http://') || url.startsWith('https://')) {
    shell.openExternal(url);
    return { action: 'deny' };
  }
  return { action: 'allow' };
});

 

こんな感じ

"use strct";

// Electronのモジュール
const electron = require("electron");
const path = require('path');

// アプリケーションをコントロールするモジュール
const app = electron.app;
const shell = electron.shell;

// ウィンドウを作成するモジュール
const BrowserWindow = electron.BrowserWindow;

// メインウィンドウはGCされないようにグローバル宣言
let mainWindow = null;

// 全てのウィンドウが閉じたら終了
app.on("window-all-closed", () => {
  if (process.platform != "darwin") {
    app.quit();
  }
});

// Electronの初期化完了後に実行
app.on("ready", () => {
  //ウィンドウサイズを750*420(フレームサイズを含まない)に設定する
  mainWindow = new BrowserWindow({
    width: 750,
    height: 420,
    resizable: false,
  	title: 'マイアプリ',
    useContentSize: true,
    icon: path.join(__dirname, 'icon.png') // アイコンのファイルパスを指定
  });
  // メニュー非表示
  //mainWindow.setMenu(null);
  //使用するhtmlファイルを指定する
  mainWindow.loadURL(`file://${__dirname}/index.html`);
//  mainWindow.loadURL(`https://wild-duck.net/cm8/`);

// 新しいウィンドウが開かれたときのハンドラーを設定
  mainWindow.webContents.setWindowOpenHandler(({ url }) => {
    if (url.startsWith('http://') || url.startsWith('https://')) {
      shell.openExternal(url);
      return { action: 'deny' };
    }
    return { action: 'allow' };
  });

  // ウィンドウが閉じられたらアプリも終了
  mainWindow.on("closed", () => {
    mainWindow = null;
  });
});

 

これで Target=_blank の時だけブラウザで開くようになる。