Home > Mobile >  How to Get # URL value with JavaScript
How to Get # URL value with JavaScript

Time:08-15

i cant use url Query https://example.com/?l=http://example2.com on my CloudFlare Worker server.

So, My question is, how to convert this JS script to work with https://example.com/#http://example2.com

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&] ([^=&] )=([^&]*)/gi,    
    function(m,key,value) {
      vars[key] = value;
    });
    return vars;
  }      

var l = getUrlVars()["l"];

Based on jp-jee reply, this my script :

            <script>
var hash = window.location.hash;
    function change(){
        var txt = hash.replace("#", "");
        document.getElementById("url").value = txt;
    }
    
     </script>
          
           <input onclick="change()"  name="url" type="text" id="url" placeholder="enter url here" value="enter url here" />
           <button id="submit" onclick="submitURL()">Submit</button>
    

Thanks :)

CodePudding user response:

Use window.location.hash and remove the # character from the result.

For the URL https://example.com/#http://example2.com, window.location.hash evauates to "#http://example2.com"

CodePudding user response:

The # and text following it is known as the "fragment" or "hash". The URL class puts this in the property .hash.

However, there is a different problem: This text is not sent to the server in regular HTTP -- it is kept only in the browser. That means that you cannot see this value in Cloudflare Workers or any other server-side code. If you want to use # for navigation, you must implement your navigation on the client side, in the browser.

  • Related