我正在使用BrowserWindow来显示应用程序,我想强制在默认浏览器中打开外部链接.这是可能的还是我必须以不同的方式处理这个问题?
小智 80
在检查了上一个答案的解决方案后,我想出了这个.
mainWindow.webContents.on('new-window', function(e, url) {
e.preventDefault();
require('electron').shell.openExternal(url);
});
Run Code Online (Sandbox Code Playgroud)
根据电子规格,new-window
点击外部链接时会触发.
注意:需要您target="_blank"
在锚标签上使用.
如果您没有target="_blank"
在anchor
元素中使用,这可能对您有用:
const shell = require('electron').shell;
$(document).on('click', 'a[href^="http"]', function(event) {
event.preventDefault();
shell.openExternal(this.href);
});
Run Code Online (Sandbox Code Playgroud)
从接受的答案中改进;
target="_blank"
;添加background.js
(或您创建窗口的任何地方):
window.webContents.on('new-window', function(e, url) {
// make sure local urls stay in electron perimeter
if('file://' === url.substr(0, 'file://'.length)) {
return;
}
// and open every other protocols on the browser
e.preventDefault();
shell.openExternal(url);
});
Run Code Online (Sandbox Code Playgroud)注意:为了确保所有应用程序窗口的这种行为,应该在每个窗口创建后运行此代码。
new-window
现在setWindowOpenHandler
在 Electron 12 中被弃用(参见https://github.com/electron/electron/pull/24517)。
因此,更新的答案是:
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12283 次 |
最近记录: |