electron#protocol TypeScript 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: app-file-protocol.ts From awakened-poe-trade with MIT License | 6 votes |
export function createFileProtocol () {
protocol.registerFileProtocol('app', (req, resp) => {
const url = new URL(req.url)
const pathName = path.join(url.host, url.pathname)
resp({ path: path.join(__dirname, pathName) })
})
protocol.registerFileProtocol('app-file', (req, resp) => {
resp({ path: path.join(app.getPath('userData'), 'apt-data/files', req.url.slice('app-file://'.length)) })
})
overlayOnEvent('OVERLAY->MAIN::import-file', (e, filePath) => {
const file = fs.readFileSync(filePath)
const hash = crypto.createHash('md5').update(file).digest('hex')
const filename = `${hash}${path.extname(filePath)}`
fs.mkdirSync(path.join(app.getPath('userData'), 'apt-data/files'), { recursive: true })
fs.writeFileSync(path.join(app.getPath('userData'), 'apt-data/files', filename), file)
e.returnValue = `app-file://${filename}`
})
}
Example #2
Source File: browser-action.ts From electron-browser-shell with GNU General Public License v3.0 | 6 votes |
private setupSession(session: Electron.Session) {
session.on('extension-loaded', (event, extension) => {
this.processExtension(extension)
})
session.on('extension-unloaded', (event, extension) => {
this.removeActions(extension.id)
})
session.protocol.registerBufferProtocol('crx', this.handleCrxRequest)
}
Example #3
Source File: index.ts From electron-playground with MIT License | 6 votes |
// 请求文件自定义协议拦截 重新设置请求链接
function registerStringProtocol() {
protocol.registerFileProtocol(
myScheme,
(request, callback) => {
// 重新拼接文件资源路径
const resolvePath = path.resolve(__dirname, '../../playground')
let url = request.url.replace( `${myScheme}://`, '' )
url = `${resolvePath}/${url}`
return callback({ path: decodeURIComponent(url) })
},
)
}
Example #4
Source File: background.ts From project_nodeSnap with GNU General Public License v3.0 | 5 votes |
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
{ scheme: "app", privileges: { secure: true, standard: true } }
]);
Example #5
Source File: background.ts From IYUU-GUI with GNU Affero General Public License v3.0 | 5 votes |
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
{ scheme: 'app', privileges: { secure: true, standard: true } }
])
Example #6
Source File: app.ts From SideQuest with MIT License | 5 votes |
function createWindow() {
appWindow = new AppWindow(config);
mainWindow = appWindow.window;
require('@electron/remote/main').enable(mainWindow.webContents);
if (process.env.NODE_ENV === 'dev') {
mainWindow.loadURL('http://localhost:4205');
mainWindow.webContents.openDevTools();
} else {
mainWindow.loadFile('build/app/index.html');
}
mainWindow.on('closed', function() {
mainWindow = undefined;
});
setupMenu();
mainWindow.webContents.once('dom-ready', async _e => {
parseOpenUrl(process.argv);
autoUpdater.autoDownload = false;
if (process.platform !== 'linux') autoUpdater.checkForUpdates();
});
protocol.registerBufferProtocol('beatsaver', (request, _callback) => {
mainWindow.webContents.send(
'open-url',
'sidequest://bsaber/#https://beatsaver.com/api/download/key/' + request.url.replace('beatsaver://', '')
);
});
protocol.registerStringProtocol('sidequest', (request, _callback) => {
mainWindow.webContents.send('open-url', request.url);
});
mainWindow.webContents.on('did-fail-load', () => mainWindow.loadURL(mainWindow.webContents.getURL()));
addWindowDownloadHandler(mainWindow);
const handleOpenWindow: (details: HandlerDetails) => { action: 'allow' } | { action: 'deny' } = e => {
if (!e.postBody) {
try {
const extUrl = new URL(e.url).host.toLowerCase();
if (OPEN_IN_SYSTEM_BROWSER_DOMAINS.includes(extUrl)) {
shell.openExternal(e.url);
return { action: 'deny' };
}
} catch (e) {
console.log('could not open url', e);
return { action: 'allow' };
}
}
return { action: 'allow' };
};
let handleWindow;
handleWindow = (child: BrowserWindow) => {
child.webContents.on('did-attach-webview', (z, wc) => {
wc.setWindowOpenHandler(handleOpenWindow);
wc.on('did-create-window', child => {
handleWindow(child);
});
});
child.webContents.setWindowOpenHandler(handleOpenWindow);
child.webContents.on('did-create-window', child => {
console.log('did create window fired');
handleWindow(child);
});
};
handleWindow(mainWindow);
mainWindow.webContents.session.setUserAgent(mainWindow.webContents.session.getUserAgent() + ' SQ/' + app.getVersion());
}
Example #7
Source File: main.ts From awakened-poe-trade with MIT License | 5 votes |
protocol.registerSchemesAsPrivileged([{ scheme: 'app', privileges: { secure: true, standard: true, supportFetchAPI: true } }])
Example #8
Source File: background.ts From cashcash-desktop with MIT License | 5 votes |
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
{ scheme: 'app', privileges: { secure: true, standard: true } },
]);
Example #9
Source File: background.ts From nodemaker with MIT License | 5 votes |
// Vue boilerplate
protocol.registerSchemesAsPrivileged([
{ scheme: "app", privileges: { secure: true, standard: true } },
]);
Example #10
Source File: electron-main.ts From yana with MIT License | 5 votes |
app.whenReady().then(() => {
protocol.registerFileProtocol('file', (request, callback) => {
const pathname = decodeURI(request.url.replace('file:///', ''));
callback(pathname);
});
});
Example #11
Source File: background.ts From elec-sqlite-vue with GNU General Public License v3.0 | 5 votes |
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
{ scheme: 'app', privileges: { secure: true, standard: true } }
])
Example #12
Source File: index.ts From electron-playground with MIT License | 5 votes |
// 需要再ready事件前调用, 并且只调用一次
protocol.registerSchemesAsPrivileged([
{ scheme: myScheme, privileges: { bypassCSP: true } },
])
Example #13
Source File: main.ts From TidGi-Desktop with Mozilla Public License 2.0 | 5 votes |
commonInit = async (): Promise<void> => {
// eslint-disable-next-line promise/catch-or-return
await app.whenReady();
if (
!protocol.registerFileProtocol('file', (request, callback) => {
const pathname = decodeURIComponent(request.url.replace('file:///', ''));
if (path.isAbsolute(pathname) ? fs.existsSync(pathname) : fs.existsSync(`/${pathname}`)) {
callback(pathname);
} else {
// on production, __dirname will be in .webpack/main
const filePath = path.join(app.getAppPath(), '.webpack', 'renderer', pathname);
callback(filePath);
}
})
) {
logger.error('Failed to registerFileProtocol file:///');
app.quit();
}
// if user want a menubar, we create a new window for that
await Promise.all([
windowService.open(WindowNames.main),
preferenceService.get('attachToMenubar').then((attachToMenubar) => {
attachToMenubar && windowService.open(WindowNames.menuBar);
}),
]);
// perform wiki startup and git sync for each workspace
await workspaceViewService.initializeAllWorkspaceView();
ipcMain.emit('request-update-pause-notifications-info');
// Fix webview is not resized automatically
// when window is maximized on Linux
// https://github.com/atomery/webcatalog/issues/561
// run it here not in mainWindow.createAsync()
// because if the `mainWindow` is maximized or minimized
// before the workspaces's BrowserView fully loaded
// error will occur
// see https://github.com/atomery/webcatalog/issues/637
// eslint-disable-next-line promise/always-return
if (process.platform === 'linux') {
const mainWindow = windowService.get(WindowNames.main);
if (mainWindow !== undefined) {
const handleMaximize = (): void => {
// getContentSize is not updated immediately
// try once after 0.2s (for fast computer), another one after 1s (to be sure)
setTimeout(() => {
void workspaceViewService.realignActiveWorkspace();
}, 200);
setTimeout(() => {
void workspaceViewService.realignActiveWorkspace();
}, 1000);
};
mainWindow.on('maximize', handleMaximize);
mainWindow.on('unmaximize', handleMaximize);
}
}
// trigger whenTrulyReady
ipcMain.emit(MainChannel.commonInitFinished);
}
Example #14
Source File: main.ts From TidGi-Desktop with Mozilla Public License 2.0 | 5 votes |
protocol.registerSchemesAsPrivileged([
{ scheme: 'http', privileges: { standard: true, bypassCSP: true, allowServiceWorkers: true, supportFetchAPI: true, corsEnabled: true, stream: true } },
{ scheme: 'https', privileges: { standard: true, bypassCSP: true, allowServiceWorkers: true, supportFetchAPI: true, corsEnabled: true, stream: true } },
{ scheme: 'mailto', privileges: { standard: true } },
]);
Example #15
Source File: main.ts From dev-manager-desktop with Apache License 2.0 | 5 votes |
function createWindow(): BrowserWindow {
// Create the browser window.
const mainWindowState = windowStateKeeper({
defaultWidth: 1024,
defaultHeight: 720
});
win = new BrowserWindow({
x: mainWindowState.x,
y: mainWindowState.y,
width: mainWindowState.width,
height: mainWindowState.height,
minWidth: 800,
minHeight: 500,
resizable: true,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInSubFrames: true,
nativeWindowOpen: true,
allowRunningInsecureContent: serve,
contextIsolation: false,
},
});
mainWindowState.manage(win);
win.setMenuBarVisibility(false);
const loadApp = () => {
if (serve) {
// win.webContents.openDevTools();
require('electron-reload')(__dirname, {
electron: require(`${__dirname}/node_modules/electron`)
});
win.loadURL('http://localhost:4210');
} else {
win.loadURL(url.format({
pathname: path.join(__dirname, 'dist/index.html'),
protocol: 'file:',
slashes: true
}));
}
};
loadApp();
// Emitted when the window is closed.
win.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.
win = null;
});
win.webContents.on('did-fail-load', () => loadApp());
skipCORS(win.webContents.session);
require('@electron/remote/main').enable(win.webContents);
const devMgr = new DeviceManagerBackend(win);
new AppManagerBackend(win);
new FileSessionBackend(win, devMgr);
new ShellSessionBackend(win, devMgr);
return win;
}