Cara menggunakan SET-LOCATION pada JavaScript

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Both location and location.href are used to set or return the complete URL of your current page. They return a string which contains the entire URL with the protocol.

    Syntax:

    location = "https://www.geeksforgeeks.org";

    or

    location.href = "https://www.geeksforgeeks.org";

    Both are used to set the URL. Both are described as running JavaScript 1.0 in the backend in Netscape 2.0 and have been running in all browsers ever since. However, you have the liberty to prefer any one of the two according to your convenience but it is preferred to use location.href because location might not support older versions of Internet Explorer. 

    Commands like location.split(“#); cannot be used as location is an object but location.href can be used as it is a string. 

    Example: The following code demonstrates the DOM Location href property.

    HTML

    <!DOCTYPE html> 

    <html

    <head>

        <style

            h2 { 

                color: green; 

            

            h2 { 

                font-family: Impact; 

            

            body { 

                text-align: center; 

            

        </style

    </head

    <body

        <h2>GeeksforGeeks</h2

        <h2>Setting location and location.href</h2

        <p

            Click on the button to go 

            to designated URL 

        </p

        <button ondblclick="myhref()">

            Destination URL

        </button

        <p id="href"></p

        <script

            function myhref() { 

               location.href =

            }

        </script

    </body

    </html>  

    Output:

    Before Clicking the Button:

    Cara menggunakan SET-LOCATION pada JavaScript

    After Double Click on Button:


    window.location.href mengembalikan lokasi halaman saat ini.

    top.location.href (yang merupakan alias dari window.top.location.href) mengembalikan lokasi jendela paling atas dalam hierarki jendela. Jika sebuah jendela tidak memiliki orangtua, top adalah referensi untuk dirinya sendiri (dengan kata lain, window === window.top).

    top berguna saat Anda berurusan dengan frame dan ketika berhadapan dengan windows yang telah dibuka oleh halaman lain. Misalnya, jika Anda memiliki halaman bernama test.html dengan skrip berikut:

    var newWin=window.open('about:blank','test','width=100,height=100');
    newWin.document.write('<script>alert(top.location.href);</script>');
    

    Lansiran yang dihasilkan akan memiliki jalur lengkap untuk test.html - tidak tentang: kosong, yang akan dikembalikan window.location.href.

    Untuk menjawab pertanyaan Anda tentang pengalihan, buka window.location.assign(url);