JAVA

Get current URL in web browser – JAVA

URL:

  • JavaScript provides many methods to retrieve and change the current URL which is displayed in browser’s address bar.
  • All these methods uses the Location object, which is a property of the Window object.

we can create a new Location object that has the current URL as follows:

Java Code
var currentLocation = window.location;

Basic Structure of a URL:

Java Code
	<protocol>//<hostname>:<port>/<pathname><search><hash>
  • Protocol – Specifies the protocol name. It is used to access the resource on the Internet. (HTTP (without SSL) or HTTPS (with SSL))
  • hostname – Host name specifies the host that owns the resource. For example, www.wikitechy.com. A server provides services using the name of the host.
  • port – A port number used to recognize a specific process to which an Internet or other network message is to be forwarded when it arrives at a server.
  • pathname – The path gives info about the specific resource within the host that the Web client needs to access. For example, /index.html.
  • query – A query string follows the path component, and provides a string of information that the resource can utilize for some purpose (for example, as parameters for a search or as data to be processed).
  • hash – The anchor portion of a URL, includes the hash sign (#).

Location object properties can access all of these URL components :

  • hash – It is used to sets or returns the anchor portion of a URL.
    var currenthash = window.location.hash;
  • host – It is used to sets or returns the hostname and port of a URL.
    var currentHost = window.location.host;
  • hostname – It is used to sets or returns the hostname of a URL.
    var currentHostname = window.location.hostname;
  • href – It is used to sets or returns the entire URL.
    var currentURL = window.location.href;
  • pathname – It is used to sets or returns the path name of a URL.
    var currentPathname = window.location.pathname;
  • port –sets or returns the port number the server uses for a URL.
    var currentPort = window.location.port;
  • protocol – It is used to sets or returns the protocol of a URL.
    var currentProtocol = window.location.protocol;
  • search – It is used to sets or returns the query portion of a URL
    var currentSearchString = window.location.search;
READ  Java Algorithm - Implement two stacks in an array

Get Current URL in Web browser:

To Get the URL From Firefox and Opera :

DdeClient dde = new DdeClient(browser, "WWW_GetWindowInfo");
dde.Connect();
string url = dde.Request("URL", int.MaxValue);
string[] text = url.Split(new string[] { "\",\"" }, StringSplitOptions.RemoveEmptyEntries);
dde.Disconnect();
return text[0].Substring(1);
 
Download NDde dll and add reference, and use as name space


//===========Get URL of All Tabs From IE ======================
Java Code
SHDocVw.InternetExplorer browser;
string myLocalLink;
mshtml.IHTMLDocument2 myDoc;
SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
string filename;
foreach (SHDocVw.InternetExplorer ie in shellWindows)
{
filename = System.IO.Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
if ((filename == "iexplore"))
{
browser = ie;
myDoc = browser.Document;
myLocalLink = myDoc.url;
MessageBox.Show(myLocalLink);
}

We can get current page URL in web browser using following code,

Java Code
Request.Url.AbsoluteUri.ToString()

Java Code
public string GetChormeURL(string ProcessName)
        {
            string ret = "";
            Process[] procs = Process.GetProcessesByName(ProcessName);
            foreach (Process proc in procs)
            {
                // the chrome process must have a window
                if (proc.MainWindowHandle == IntPtr.Zero)
                {
                    continue;
                }
                //AutomationElement elm = AutomationElement.RootElement.FindFirst(TreeScope.Children,
                //         new PropertyCondition(AutomationElement.ClassNameProperty, "Chrome_WidgetWin_1"));
                // find the automation element
                AutomationElement elm = AutomationElement.FromHandle(proc.MainWindowHandle);
Java Code
 // manually walk through the tree, searching using TreeScope.Descendants is too slow (even if it's more reliable)
                AutomationElement elmUrlBar = null;
                try
                {
                    // walking path found using inspect.exe (Windows SDK) for Chrome 43.0.2357.81 m (currently the latest stable)
                    // Inspect.exe path - C://Program files (X86)/Windows Kits/10/bin/x64
                    var elm1 = elm.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Google Chrome"));
                    if (elm1 == null) { continue; } // not the right chrome.exe
                    var elm2 = TreeWalker.RawViewWalker.GetLastChild(elm1); // I don't know a Condition for this for finding
Java Code
 var elm3 = elm2.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, ""));
                    var elm4 = TreeWalker.RawViewWalker.GetNextSibling(elm3); // I don't know a Condition for this for finding
                    var elm5 = elm4.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ToolBar));
                    var elm6 = elm5.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, ""));
                    elmUrlBar = elm6.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
                }
                catch
                {
                    // Chrome has probably changed something, and above walking needs to be modified. :(
                    // put an assertion here or something to make sure you don't miss it
                    continue;
                }
Java Code
 // make sure it's valid
                if (elmUrlBar == null)
                {
                    // it's not..
                    continue;
                }

                // elmUrlBar is now the URL bar element. we have to make sure that it's out of keyboard focus if we want to get a valid URL
                if ((bool)elmUrlBar.GetCurrentPropertyValue(AutomationElement.HasKeyboardFocusProperty))
                {
                    continue;
                }

                // there might not be a valid pattern to use, so we have to make sure we have one
java Code
 AutomationPattern[] patterns = elmUrlBar.GetSupportedPatterns();
                if (patterns.Length == 1)
                {
                    try
                    {
                        ret = ((ValuePattern)elmUrlBar.GetCurrentPattern(patterns[0])).Current.Value;
                        return ret;
                    }
 catch { }
                    if (ret != "")
                    {
                        // must match a domain name (and possibly "https://" in front)
                        if (Regex.IsMatch(ret, @"^(https:\/\/)?[a-zA-Z0-9\-\.]+(\.[a-zA-Z]{2,4}).*$"))
                        {
                            // prepend http:// to the url, because Chrome hides it if it's not SSL
                            if (!ret.StartsWith("http"))
                            {
                                ret = "http://" + ret;
                            }
Java Code
 return ret;
                        }
                    }
                    continue;
                }
            }
            return ret;
        }

To get the path, we can use the method:

Java Code
alert("Url  ="+document.location);
alert("PathName  ="+ window.location.pathname);// Returns path only
alert("url  ="+window.location.href);// Returns full URL

Use window.location.href to get the complete URL.
Use window.location.pathname to get URL leaving the host.

READ  [ Solution 1 Answers ] Class Is Public, Should Be Declared In A File Named .Java

For complete URL with query strings:

Java Code
document.location.toString().toLowerCase();

For host URL:

Java Code
window.location

About the author

Wikitechy Editor

Wikitechy Editor

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

X