1

I have a "on click" window.location.assign function that is working fine on my desktop but not on the iPhone. Each time I click on the button on my phone, I see that the URL is changing but then coming back to the old one.

I tried with window.location.replace and other JS options to make a redirection but there was always this strange "bug" on my phone.

    $('#redirect').on('click', function(){
      var url = "https://google.com/";
      window.location.assign(url);
      return false;
    });

Why is this happening and how can it be resolved?

Kyle Dormer
  • 39
  • 10
Wojciech
  • 103
  • 1
  • 3
  • 12
  • I don't know why this doesn't work, but shouldn't changing `location.href` work? – evolutionxbox May 21 '19 at 12:56
  • [MDN seems to think it works on iOS](https://developer.mozilla.org/en-US/docs/Web/API/Location/assign). Is `#redirect` a button? – evolutionxbox May 21 '19 at 12:58
  • Is #redirect I link or button or something? You aren’t preventing default, and I’ll bet the original action of this element (causing some sort of page load) is occurring before your JavaScript. The second Safari starts loading another page, it freezes the page. You have to preventDefault() if this element does something natively. EDIT: I just saw the return false. Does preventDefault change anything? – Nate May 21 '19 at 13:09
  • I'm also thinking that iOS may not even be triggering the event. See https://stackoverflow.com/questions/14795944/jquery-click-events-not-working-in-ios and https://stackoverflow.com/questions/3025348/how-do-i-use-jquery-for-click-event-in-iphone-web-application – evolutionxbox May 21 '19 at 13:10
  • @evolutionxbox Oohh. Yeah I could see that. – Nate May 21 '19 at 13:11
  • the #redirect can be a button or a div with cursor:pointer... nothing is working – Wojciech May 21 '19 at 13:20
  • Can you console log from inside the click event? Do you see the logs? – evolutionxbox May 21 '19 at 13:20

1 Answers1

0

Safari on iOS is bad. If you want to detect safari and redirect using something that will work, try this:

var url = "https://google.com/";
var uagent = navigator.userAgent.toLowerCase();
if(/safari/.test(uagent) && !/chrome/.test(uagent)) {
    window.location.href = url;
}
VirxEC
  • 998
  • 10
  • 22