Javascript/jQuery:以编程方式跟随链接 [英] Javascript/jQuery: programmatically follow a link
问题描述
在 Javascript 代码中,我想以编程方式使浏览器跟随我页面上的链接.简单案例:
In Javascript code, I would like to programmatically cause the browser to follow a link that's on my page. Simple case:
<a id="foo" href="mailto:somebody@example.com">something</a>
<小时>
function goToBar() {
$('#foo').trigger('follow');
}
这是假设的,因为它实际上不起作用.不,触发 click
不会这样做.
This is hypothetical as it doesn't actually work. And no, triggering click
doesn't do it.
我知道 window.location
和 window.open
但它们在某些对我很重要的方面与本机链接跟踪不同:a) 在存在a
元素,以及 b) 在 mailto
URL 的情况下.后者尤其重要.至少在 Firefox 中,调用 window.location.href = "mailto:somebody@example.com"
会导致窗口的 unload
处理程序触发,而只需单击 mailto
链接没有,据我所知.
I am aware of window.location
and window.open
but these differ from native link-following in some ways that matter to me: a) in the presence of a <base />
element, and b) in the case of mailto
URLs. The latter in particular is significant. In Firefox at least, calling window.location.href = "mailto:somebody@example.com"
causes the window's unload
handlers to fire, whereas simply clicking a mailto
link does not, as far as I can tell.
我正在寻找一种从 Javascript 代码触发浏览器默认链接处理的方法.
I'm looking for a way to trigger the browser's default handling of links, from Javascript code.
这种机制存在吗?也欢迎提供特定于工具包的答案(尤其是 Gecko).
Does such a mechanism exist? Toolkit-specific answers also welcome (especially for Gecko).
推荐答案
据我所知,window.location 完全符合您的要求,触发浏览器的默认链接点击行为.
As far as I know, window.location does exactly what you are looking for, triggering the browser's default link clicking behavior.
某些浏览器会在触发任何事件或更改实际 href 之前注意到该协议.
Some browsers notice the protocol before any events are fired or the actual href is changed.
window.location = "mailto:somebody@example.com";
尝试下面提到的小提琴演示,我得到以下结果:
Trying the fiddle demo mentioned below I get the following results:
- Chromium:使用按钮和链接触发
onbeforeunload
- Firefox 仅针对按钮触发
onbeforeunload
- Safari:从不触发
onbeforeunload
- Opera:与 Safari 相同
因此,防止 unload
事件被触发的一个好方法是在 beforeunload
中返回 false.
So a good way to prevent the unload
event from being fired is by returning false in beforeunload
.
这篇关于Javascript/jQuery:以编程方式跟随链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!