Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

html - Redirect to a new windows, with JavaScript, with a onclick on <a></a>

I was making this code to insert it into my website, to detect the OS from the devices, and depending which OS they have, redirect to different pages. Also, if I upload the code to my website, the href doesn't work really well, and it searches https://example.com/thehref instead of the href alone.

This is what I have been doing, to solve the problem.

<script>

  var OSName = "Unknown OS";
    if (navigator.userAgent.indexOf("Win") != -1) OSName = 1;
    if (navigator.userAgent.indexOf("Mac") != -1) OSName = 0;
    if (navigator.userAgent.indexOf("Linux") != -1) OSName = 1;
    if (navigator.userAgent.indexOf("Android") != -1) OSName = 1;
    if (navigator.userAgent.indexOf("like Mac") != -1) OSName = 0;

    if (OSName == 1) OSName = "play.google.com";
    if (OSName == 0) OSName = "apps.apple.com";


</script>

<a href="https://www.google.com" onclick="location.href=this.href+OSName;return false;"> <p>Click<br> at me!!!</p> </a>
question from:https://stackoverflow.com/questions/65881162/redirect-to-a-new-windows-with-javascript-with-a-onclick-on-a-a

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Please try this one.

<script>
  var OSName = "Unknown OS";

  if (navigator.userAgent.indexOf("Win") != -1) OSName = 1;
  if (navigator.userAgent.indexOf("Mac") != -1) OSName = 0;
  if (navigator.userAgent.indexOf("Linux") != -1) OSName = 1;
  if (navigator.userAgent.indexOf("Android") != -1) OSName = 1;
  if (navigator.userAgent.indexOf("like Mac") != -1) OSName = 0;

  if (OSName == 1) OSName = "page1";
  if (OSName == 0) OSName = "page2";

  function openPage() {
    window.open(window.location.href + '/' + OSName);
    return false;
  }
</script>

<a href="https://" onclick="openPage()"> <p>Click<br> at me!!!</p> </a>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...