使用onbeforeunload事件,在此页面上选择停留时更改URL [英] using onbeforeunload event, url change on selecting stay on this page
问题描述
重写问题 -
我正在尝试创建一个页面,如果用户离开页面(到其他链接/网站或关闭窗口/标签)我想显示 onbeforeunload
handeler说我们有一个很棒的报价?
如果用户选择离开页面
它应该做正常的传播,但如果他选择留在页面上
我需要他将其重定向到提供页面重定向很重要,没有妥协
。对于测试,我们可以重定向到 google.com
I am trying to make a page on which if user leave the page (either to other link/website or closing window/tab) I want to show the onbeforeunload
handeler saying we have a great offer for you?
and if user choose to leave the page
it should do the normal propogation but if he choose to stay on the page
I need him to redirect it to offer page redirection is important, no compromise
. For testing lets redirect to google.com
我制作了一个程序如下 -
I made a program as follows -
var stayonthis = true;
var a;
function load() {
window.onbeforeunload = function(e) {
if(stayonthis){
a = setTimeout('window.location.href="http://google.com";',100);
stayonthis = false;
return "Do you really want to leave now?";
}
else {
clearTimeout(a);
}
};
window.onunload = function(e) {
clearTimeout(a);
};
}
window.onload = load;
但问题是,如果他点击 yahoo.com的链接
并选择离开页面
他不会去雅虎而是google :(
but the problem is that if he click on the link to yahoo.com
and choose to leave the page
he is not going to yahoo but to google instead :(
帮助我!!提前致谢
这里是如何测试的,因为onbeforeunload对iframe不起作用
推荐答案
此解决方案适用于所有情况,使用后退浏览器按钮,在地址栏中设置新网址或使用链接。
我发现触发onbeforeunload处理程序不会显示附加到onbeforeunload处理程序的对话框。
在这种情况下(当需要触发时),使用确认框显示用户消息。此解决方法在chrome / firefox和IE(7到10)中测试
This solution works in all cases, using back browser button, setting new url in address bar or use links. What i have found is that triggering onbeforeunload handler doesn't show the dialog attached to onbeforeunload handler. In this case (when triggering is needed), use a confirm box to show the user message. This workaround is tested in chrome/firefox and IE (7 to 10)
<罢工> http://jsfiddle.net/W3vUB/4/show
http://jsfiddle.net/W3vUB/4/show
http://jsfiddle.net/W3vUB/ 4 /
http://jsfiddle.net/W3vUB/4/
编辑:在codepen上设置DEMO,显然jsFiddle不喜欢这个片段(?! )
BTW,使用 bing.com
,因为谷歌不允许在iframe中显示更多内容。
set DEMO on codepen, apparently jsFiddle doesn't like this snippet(?!)
BTW, using bing.com
due to google not allowing no more content being displayed inside iframe.
http://codepen.io/anon/pen/dYKKbZ
var a, b = false,
c = "http://bing.com";
function triggerEvent(el, type) {
if ((el[type] || false) && typeof el[type] == 'function') {
el[type](el);
}
}
$(function () {
$('a:not([href^=#])').on('click', function (e) {
e.preventDefault();
if (confirm("Do you really want to leave now?")) c = this.href;
triggerEvent(window, 'onbeforeunload');
});
});
window.onbeforeunload = function (e) {
if (b) return;
a = setTimeout(function () {
b = true;
window.location.href = c;
c = "http://bing.com";
console.log(c);
}, 500);
return "Do you really want to leave now?";
}
window.onunload = function () {
clearTimeout(a);
}
这篇关于使用onbeforeunload事件,在此页面上选择停留时更改URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!