简体   繁体   中英

Recieve data into javascript from entered url to webpage

I have a webpage that alerts me the with the current .href of the website. However I want to be able to pass a short variable into the webpage when entering the domain name so that I later can use that in js.

For example going to website localhost entering: localhost/HelloWorld should alert " HelloWorld "

Is this possible?

This is my html code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Get Current URL in JavaScript</title>
</head>
<body>
    <script>
    function getURL() {
        alert("The URL of this page is: " + window.location.href);
    }
    </script>

    <button type="button" onclick="getURL();">Get Page URL</button>
</body>
</html>

Simply using pathname property should do it for you. The location object contains all the host and paths in it.

<script>
function getURLPath() {
    alert("The URL path of this page is: " + window.location.pathname);
}
</script>

Assuming that the address is https://localhost/HelloWorld , try window.location.pathname.split('/')[1] .

pathname is the string /HelloWorld that comes after the domain localhost . Using split you can split it into parts (in this case two). The first part will always be an empty string. The second part will be the string HelloWorld in this case.

For this to work, the web server has to serve index.html on all paths. That's standard behavior for Node. Otherwise, you will want to edit your web server's configuration files.

If you go to localhost/HelloWorld the server will try to locate the HelloWorld page, which doesn't exist. Instead the correct way to pass a parameter to a page is through a query string , for instance: localhost?q=HelloWorld . You could also redirect localhost/HelloWorld to localhost?q=HelloWorld using a custom router, depending on your server, for instance using a .htaccess file, if using Apache.

You retrieve the parameter using window.location.search or converting to URL object and using searchParams .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM