Search code examples
javascriptgoogle-chromebookmarklet

Get browser URL box contents with JavaScript


I want to make a bookmarklet that will take me to isup.me and check the site that wouldn't load.

So basically it would be like running this in the console:

window.location.href = "http://isup.me/" + window.location.host;

Which is supposed to navigate me to http://isup.me/site_I_want_to_check

This works fine for sites that are already loaded, but fails on sites that won't load. Here is window.location.href containing the string that is shown in the address bar: enter image description here

And here is window.location.href on a site that can't be reached: enter image description here

As you can see in the above screenshot, the value of window.location.href does not match what is displayed in the address field. Instead of returning "http://www.minetest.net" I get "data:text/html,chromewebdata" and when I look at the value of window.location.host it actually returns a blank string.

How can I get the visible contents of the address bar with JavaScript while viewing Chrome's internal fail webpage informing me that a site cannot be reached?


Solution

  • Assuming you're on Chrome you can extract the attempted URL from the title element:

    function url() {
      if(window.location.href=='data:text/html,chromewebdata') {
        return document.title.match(/([^ ]*)/).pop();
      }else{
        return document.location.href;
      }
    }