electron中的a标签默认会在electron窗口中打开,如果我们想让页面中所有的a标签都在浏览器打开,该怎么做呢?
只要在页面中加入以下代码:
const links
= document
.querySelectorAll
('a[href]');
links
.forEach(link => {
link.addEventListener
('click', e
=> {
const url
= link.getAttribute
('href');
e
.preventDefault
();
const { shell
} = require('electron');
shell
.openExternal
(url
);
});
});
值得注意的是,这段代码需要在页面元素渲染完成后执行。
可以放在window.onload中执行:
window
.onload
=function(){
const links
= document
.querySelectorAll
('a[href]');
links
.forEach(link => {
link.addEventListener
('click', e
=> {
const url
= link.getAttribute
('href');
e
.preventDefault
();
const { shell
} = require('electron');
shell
.openExternal
(url
);
});
});
}
如果使用了jquery,可以放在$(document).ready()中执行:
$
(document
).ready
(function(){
const links
= document
.querySelectorAll
('a[href]');
links
.forEach(link => {
link.addEventListener
('click', e
=> {
const url
= link.getAttribute
('href');
e
.preventDefault
();
const { shell
} = require('electron');
shell
.openExternal
(url
);
});
});
});
如果使用了vue,可以放在mounted生命周期中执行
mounted
(){
const links
= document
.querySelectorAll
('a[href]');
links
.forEach(link => {
link.addEventListener
('click', e
=> {
const url
= link.getAttribute
('href');
e
.preventDefault
();
const { shell
} = require('electron');
shell
.openExternal
(url
);
});
});
}