最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - href links not working with onclick events in Safari - Stack Overflow

programmeradmin1浏览0评论
<script type="text/javascript">
function ref() {
    location.href = '';
}
</script>

<a target="_blank" href="/somepage.html" onclick="javascript:ref()">CLICK ME</a>

In Chrome, FF and IE, clicking the link will open Google in the current window and open somepage.html in a new tab/window

But in Safari it will just open Google in the current window and nothing else.

How can I make Safari replicate the other browsers?

<script type="text/javascript">
function ref() {
    location.href = 'http://www.google.';
}
</script>

<a target="_blank" href="/somepage.html" onclick="javascript:ref()">CLICK ME</a>

In Chrome, FF and IE, clicking the link will open Google in the current window and open somepage.html in a new tab/window

But in Safari it will just open Google in the current window and nothing else.

How can I make Safari replicate the other browsers?

Share Improve this question asked Jan 5, 2015 at 15:35 Gixxy22Gixxy22 5071 gold badge8 silver badges20 bronze badges 5
  • Not probably a solution, but a ment: it's just onclick="ref()" without javascript: – Samuli Hakoniemi Commented Jan 5, 2015 at 15:44
  • thanks, edited, didnt make any difference but thanks for pointing that out. – Gixxy22 Commented Jan 5, 2015 at 15:46
  • possible duplicate of HTML anchor tag with Javascript onclick event – Vitalii Zurian Commented Jan 5, 2015 at 15:48
  • Using the developers tool in Safari, is there any error in the console? – Ofir Baruch Commented Jan 5, 2015 at 16:03
  • Nope, no errors or warnings at all. – Gixxy22 Commented Jan 5, 2015 at 16:05
Add a ment  | 

1 Answer 1

Reset to default 4

location.href will only change the URL of the current window. In order to open a new tab or window, its better to use window.open. I tested it in Safari specifically (and Chrome) and it is working in both browsers.

<a href="/somepage.html" onclick="javascript:ref()">CLICK ME</a>


<script type="text/javascript">
function ref() {
    window.open('http://www.google.', '_blank');
}
</script>

The way you had it written, somepage.html will open in a new tab and the current page will redirect to google. If you want it that way just switch the URLs around like so:

<a href="www.google." onclick="javascript:ref()">CLICK ME</a>


<script type="text/javascript">
function ref() {
    window.open('/somepage.html', '_blank');
}
</script>

A side note, I found out that Safari allows user to handle how they want windows opening, whether it be a new window or a tab, and unfortunately we do not have any control over that.

发布评论

评论列表(0)

  1. 暂无评论