Window Location JavaScript
- Page précédente Écran JS
- Page suivante Histoire JS
L'objet window.location peut être utilisé pour obtenir l'adresse (URL) de la page actuelle et rediriger le navigateur vers une nouvelle page.
Window Location
window.location L'objet peut être écrit sans préfixe window.
Certains exemples :
- window.location.href retourne l'href (URL) de la page actuelle
- window.location.hostname retourne le domaine du nom d'hôte web
- window.location.pathname retourne le chemin ou le nom du fichier de la page actuelle
- window.location.protocol retourne le protocole web utilisé (http: ou https:)
- window.location.assign charge un nouveau document
Href de Window Location
window.location.href
L'attribut retourne l'URL actuel de la page.
Exemple
Afficher l'href (URL) actuel de la page :
document.getElementById("demo").innerHTML = "La position de la page est " + window.location.href;
Le résultat est :
La position de la page est http://www.codew3c.com/js/js_window_location.asp
Nom d'hôte de Window Location
window.location.hostname
L'attribut retourne le nom de l'hôte Internet (ducurrent page).
Exemple
Afficher le nom de l'hôte :
document.getElementById("demo").innerHTML = "Le nom d'hôte de la page est " + window.location.hostname;
Le résultat est :
Le nom d'hôte de la page est www.codew3c.com
Chemin de Window Location
window.location.pathname
L'attribut retourne le chemin actuel de la page.
Exemple
Afficher le chemin actuel de l'URL :
document.getElementById("demo").innerHTML = "Le chemin de la page est " + window.location.pathname;
Le résultat est :
Le chemin de la page est /js/js_window_location.asp
Protocole de Window Location
window.location.protocol
L'attribut retourne le protocole web de la page.
Exemple
Afficher le protocole web :
document.getElementById("demo").innerHTML = "Le protocole de page est " + window.location.protocol;
Le résultat est :
Le protocole de page est http:
Port Window Location
window.location.port
L'attribut retourne le numéro du port de l'hôte Internet (du site web actuel).
Exemple
Afficher le port de l'hôte principal :
document.getElementById("demo").innerHTML = "Le port est : " + window.location.port;
La plupart des navigateurs ne montrent pas le port par défaut (http est 80, https est 443).
Window Location Assign
window.location.assign()
Méthode pour charger un nouveau document.
Exemple
Charger un nouveau document :
<html> <head> <script> function newDoc() { window.location.assign("https://www.codew3c.com") } </script> </head> <body> <input type="button" value="Charger un nouveau document" onclick="newDoc()"> </body> </html>
- Page précédente Écran JS
- Page suivante Histoire JS