方案1: 使用iframe 结合 通过父调用子方法,让父窗口获取焦点;(适合1个页面)
必须满足条件1:当前页面必须用户点击或与Dom发生或一次交互;否则会报错没有权限;
简单解释一下谷歌2018的安全策略:(有的狗子总要问个为什么?) 用户已经与当前页面进行了交互(click、tap),就是点击或者滚动,必须由用户主动触发;否则程序没有权限使用;
// 父页面 index.html
<iframe id="myIframe" src="./wakeUp.html"></iframe>
// 注意这里要指定window.name
window.name = 'bbsPage'
function callChildMethod() {
var iframe = document.getElementById('myIframe');
if (iframe.contentWindow) {
iframe.contentWindow.wakeUpParent();
};
}
// 模拟5秒后收到消息
setTimeout(() => {
callChildMethod();
}, 5000);
// 子页面 wakeUp.html
function wakeUpParent() {
window.open("", window.parent.name).focus();
}
方案2: 使用window.open()打开页面,然后调用focus()获取焦点;(适合2个页面及以上)
必须满足条件1:当前页面必须用户点击或与Dom发生或一次交互;否则会报错没有权限;
let myWindow = null;
function openFirefoxWin(){
myWindow = window.open('', '_blank');
myWindow.document.write("<p>这里是新打开的Firefox窗□</p>");
myWindow.focus();
// 如果担心当前页面刷新myWindow对象丢失
window.name = 'topPage';
}
openFirefoxWin();
// 模拟收到一条消息
setTimeout(() => {
myWindow && myWindow.focus && myWindow.focus();
}, 5000);
// 如果刷新后myWindow对象丢失了可以使用
window.open('javascript:;', 'topPage');
方案3:通过切换全屏切换实现,但必须满足2个条件;(适合2个页面及以上)
必须满足条件1:当前页面必须是浏览器tab页的显示页面;
// 否则报错
Uncaught (in promise)
TypeError: not granted
必须满足条件2:当前页面必须用户点击或与Dom发生或一次交互;
// 否则报错
Uncaught (in promise)
TypeError: Permissions check failed
方案Demo
<div id="activateId" style="display: none;"></div>
<script>
var element = document.getElementById('activateId');
element.addEventListener('fullscreenchange', function() {
if (document.fullscreenElement) {
console.log('进入全屏模式');
// 执行进入全屏模式后的操作
closeFullscreen();
} else {
console.log('退出全屏模式');
// 执行退出全屏模式后的操作
}
});
function openFullscreen() {
if (document.fullscreenElement) {
// 如果已经是全屏,则退出
closeFullscreen();
} else {
// 尝试进入全屏模式
var elem = document.getElementById('activateId');
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) { /* Firefox */
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
elem.webkitRequestFullscreen();
} else if (elem.msRequestFullscreen) { /* IE/Edge */
elem.msRequestFullscreen();
}
}
}
function closeFullscreen() {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) { /* Firefox */
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) { /* Chrome, Safari and Opera */
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) { /* IE/Edge */
document.msExitFullscreen();
}
}
// 模拟收到一条消息
setTimeout(() => {
openFullscreen();
}, 5000);
</script>