electron#protocol JavaScript Examples

The following examples show how to use electron#protocol. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: main.js    From ioHookElectronWebpack with MIT License 6 votes vote down vote up
app.on("ready", async () => {
  try {
    globalShortcut.register('Control+Shift+I', () => {
      if (mainWindow.webContents.isDevToolsOpened()) {
        mainWindow.webContents.closeDevTools()
      } else {
        mainWindow.webContents.openDevTools();
      }
    });

    //protocol.interceptFileProtocol('file', (request, callback) => {
      //const url = request.url.substr(7)    /* all urls start with 'file://' */
      //callback({ path: path.normalize('${__dirname}/${url}')})
    //});

    // Name the protocol whatever you want
    const protocolName = 'safe-file-protocol';

    // NEEDED FOR PROPER IMAGES LOADING
    protocol.registerFileProtocol(protocolName, (request, callback) => {
      const url = request.url.replace(`${protocolName}://`, '');
      try {
        return callback(decodeURIComponent(url))
      } catch (error) {
        // Handle the error as needed
        log.error(error)
      }
    });

    createWindow();
  } catch (error) {
    log.error(error);
    ioHook.stop();
    app.quit();
  }
});
Example #2
Source File: resource-loader.js    From Memocast with MIT License 6 votes vote down vote up
export function registerMemocastProtocol () {
  protocol.registerStreamProtocol(
    'memocast',
    async (request, callback) => {
      //
      const result = await resourceProtocolHandler(request, callback)
      return result
      //
    },
    error => {
      if (error) {
        console.error(`Failed to register protocol: ${error.message}`)
      }
    }
  )
}
Example #3
Source File: library-files.js    From desktop with GNU General Public License v3.0 6 votes vote down vote up
app.whenReady().then(() => {
  protocol.registerBufferProtocol('tw-library-files', (request, callback) => {
    const md5ext = new URL(request.url).pathname;
    decompressAsset(md5ext)
      .then((data) => {
        callback({
          data: data.data,
          mimeType: data.type
        });
      })
      .catch(() => {
        callback({
          statusCode: 404
        });
      });
  });
});
Example #4
Source File: background.js    From melvor-mod-manager with MIT License 5 votes vote down vote up
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
]);
Example #5
Source File: main.js    From ioHookElectronWebpack with MIT License 5 votes vote down vote up
function createWindow() {
  const size = screen.getPrimaryDisplay().workAreaSize;

  // Create the browser window.
  mainWindow = new BrowserWindow({
    x: 200,
    y: 200,
    width: /*320*/ /*800*/ 640,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      allowRunningInsecureContent: serve,
      contextIsolation: false,
      enableRemoteModule : true,
      devTools: true
    },
  });

  mainWindow.setAlwaysOnTop(true, 'floating');
  mainWindow.setVisibleOnAllWorkspaces(true);
  mainWindow.setFullScreenable(false);

  if (serve) {
    //mainWindow.webContents.openDevTools();
    mainWindow.loadFile(path.join(__dirname, "./../src/index.html"));

  } else {
    mainWindow.loadURL(url.format({
      pathname: path.join(__dirname, './../src/index.html'),
      protocol: 'file:',
      slashes: true
    }));
  }

  /**
   * Need to deal with Electron bug when window not closing wit open developer tools
   * And frame mode set to false. False frame mode needed wor default window tilebar
   */
  mainWindow.on('close', () => {
    ioHook.stop();

    if (mainWindow.webContents.isDevToolsOpened()) {
      mainWindow.webContents.closeDevTools()
    }
  });

  // Emitted when the window is closed.
  mainWindow.on('closed', () => {
    // Dereference the window object, usually you would store window
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });

  return mainWindow;
}
Example #6
Source File: background.js    From cesium-vue-electron with MIT License 5 votes vote down vote up
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([{ scheme: 'app', privileges: { secure: true, standard: true } }])
Example #7
Source File: library-files.js    From desktop with GNU General Public License v3.0 5 votes vote down vote up
protocol.registerSchemesAsPrivileged([
  {
    scheme: 'tw-library-files',
    privileges: {
      supportFetchAPI: true
    }
  }
]);
Example #8
Source File: background.js    From mogollar with MIT License 5 votes vote down vote up
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([{ scheme: 'app', privileges: { secure: true, standard: true } }])
Example #9
Source File: background.js    From dev-sidecar with Mozilla Public License 2.0 5 votes vote down vote up
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])
Example #10
Source File: background.js    From wl-admin with MIT License 5 votes vote down vote up
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: "app", privileges: { secure: true, standard: true } }
]);
Example #11
Source File: background.js    From linked with GNU General Public License v3.0 5 votes vote down vote up
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])
Example #12
Source File: background.js    From vupc with MIT License 5 votes vote down vote up
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: "app", privileges: { secure: true, standard: true } },
]);
Example #13
Source File: background.js    From EveReader with GNU Affero General Public License v3.0 5 votes vote down vote up
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: "app", privileges: { secure: true, standard: true } },
]);
Example #14
Source File: index.js    From zengm-legacy with Apache License 2.0 5 votes vote down vote up
createWindow = () => {
    // Rewrite URLs to handle host-relative URLs, which begin with a slash.
    protocol.registerBufferProtocol(scheme, (req, callback) => {
        let reqUrl = url.parse(req.url);
        let pathname = reqUrl.pathname;
        if (pathname.endsWith('/')) pathname += 'index.html';
        if (reqUrl.hostname === hostname) {
            let filePath = path.normalize(pathname);
            if (startsWith(filePath, prefixesStaticWithHtml)) {
                filePath += '.html';
            }
            filePath = path.join(webroot, filePath);

            fs.access(filePath, fs.constants.R_OK, (err) => {
                if (err) {
                    console.error(err);
                    callback(404);
                } else {
                    callback({
                        mimeType: mimeType(pathname), charset: 'UTF-8',
                        data:     fs.readFileSync(filePath)
                    });
                }
            });
        } else {
            serveLocalMirror(reqUrl, callback);
        }
    }, (err) => {
        if (err) console.error('ERROR: failed to register protocol', scheme);
    });
    protocol.registerServiceWorkerSchemes([scheme]);

    // Create the browser window.
    // https://electron.atom.io/docs/api/browser-window/
    mainWindow = new BrowserWindow({
        width: 1024, height: 768, backgroundColor: '#203C64',
        center:true, fullscreen:false,
        title: app.getName(),
        webPreferences: {
            nodeIntegration:false,
            preload: path.join(__dirname, 'preload.js')
        }
    });

    // and load the index.html of the app.
    mainWindow.loadURL(`${scheme}://${hostname}/`);

    // Open external URLs in the browser:
    mainWindow.webContents.on('will-navigate', (event, url) => {
        event.preventDefault();
        shell.openExternal(url);
    });

    // Open the DevTools.
    process.argv.some((arg) => {
        if (arg === '--dev') {
            mainWindow.webContents.openDevTools();
            return true;
        }
        return false;
    });

    // Implement window.prompt() and window.confirm() which are used by ZenGM:
    ipcMain.on('prompt', prompt);
    ipcMain.on('prompt-response', promptResponse);
    ipcMain.on('confirm', confirm);
    ipcMain.on('confirm-response', confirmResponse);

    // Emitted when the window is closed.
    mainWindow.on('closed', () => {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null;
    });
}
Example #15
Source File: index.js    From zengm-legacy with Apache License 2.0 5 votes vote down vote up
protocol.registerStandardSchemes([scheme], { secure:true });
Example #16
Source File: electron-main.js    From Memocast with MIT License 4 votes vote down vote up
function createWindow () {
  const mainWindowState = windowStateKeeper({
    defaultWidth: 900,
    defaultHeight: 600
  })
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    x: mainWindowState.x,
    y: mainWindowState.y,
    width: mainWindowState.width < 600 ? 600 : mainWindowState.width,
    height: mainWindowState.height < 400 ? 400 : mainWindowState.height,
    useContentSize: true,
    // transparent: true,
    vibrancy: ThemeManager.colorMode, // 'light', 'medium-light' etc
    webPreferences: {
      // Change from /quasar.conf.js > electron > nodeIntegration;
      // More info: https://quasar.dev/quasar-cli/developing-electron-apps/node-integration
      nodeIntegration: true,
      contextIsolation: false,
      nodeIntegrationInWorker: process.env.QUASAR_NODE_INTEGRATION,
      webSecurity: false,
      experimentalFeatures: false,
      enableRemoteModule: true

      // More info: /quasar-cli/developing-electron-apps/electron-preload-script
      // preload: path.resolve(__dirname, 'electron-preload.js')
    },
    frame: false,
    titleBarStyle: 'hiddenInset'
  })

  protocol.interceptFileProtocol('file', (req, callback) => {
    const url = req.url.substr(8)
    callback(decodeURI(url))
  }, (error) => {
    if (error) {
      console.error('Failed to register protocol')
    }
  })

  registerMemocastProtocol()

  if (!process.env.PROD) {
    mainWindow.webContents.openDevTools()
  }
  const menu = Menu.buildFromTemplate(configureMenu(new KeyBindings(), mainWindow))
  Menu.setApplicationMenu(menu)

  mainWindow.isMainWindow = true
  mainWindowState.manage(mainWindow)

  mainWindow.loadURL(process.env.APP_URL).then()
  // mainWindow.on('closed', () => {
  //   mainWindow = null
  // })
  mainWindow.on('close', (event) => {
    if (!forceQuit) {
      event.preventDefault() // This will cancel the close
      mainWindow.hide()
    }
  })

  mainWindow.on('closed', () => {
    mainWindow = null
  })

  mainWindow.webContents.on('new-window', (event, linkUrl) => {
    event.preventDefault()
    if (linkUrl.startsWith('http://localhost:') || linkUrl.startsWith('file://')) {
      // dialog.showErrorBox('Unsupported Url Protocol', `Memocast cannot resolve this protocol: ${linkUrl}, please copy it to browser manually!`)
      return
    }
    dialog.showMessageBox(mainWindow, {
      type: 'question',
      title: i18n.t('openLinkHint'),
      message: i18n.t('openLinkHint'),
      detail: linkUrl,
      buttons: [i18n.t('confirm'), i18n.t('cancel')]
    }).then((res) => {
      if (!res.response) {
        shell.openExternal(linkUrl).then()
      }
    })
  })
  registerApiHandler()
  global.themeManager = ThemeManager
  if (isMac) {
    enforceMacOSAppLocation()
  }

  require('@electron/remote/main').initialize()
  require('@electron/remote/main').enable(mainWindow.webContents)
}