Index | PHP | CSS | JS | Feature
JS - JavaScript - General URL and Address Solutions
There are several ways to get information about the address of the server running the JS script:
Let's start with something pretty simple:
// Using built-in browser functions:
// Create an anchor element (just for JS manipulation, this never gets appended to the document )
const url = document.createElement('a');
// Set href to any path
url.setAttribute('href', 'https://www.myexample.org:443/pmwiki/code/snippets?action=edit&username=Phred');
// That's it!
// The browser's built-in parser has already done its job.
// Now you can just grab the parts you need:
// Get any piece of the url you're interested in
url.hostname; // myexample.org
url.port; // 443
url.search; // ?action=edit&username=Phred
url.pathname; // /pmwiki/code/snippets
url.protocol; // https:
//For Example:
echo url.hostname; // here should return: snippetspub.com
Since the Script is likely to be included by a reference within the HTML document
We may want to know where the actual JavaScript file is located.
/** This routine tries the second method if the first fails **/
/** Get the url for the current script (this file): **/
var scripts = document.getElementsByTagName("script") ;
/** This code should be in the latest script loaded, so: **/
var ScriptSRC = scripts[scripts.length-1].src ; //URL of this Script
if(typeof(ScriptSRC) === "undefined" || ScriptSRC === null || ScriptSRC === "") {
ScriptSRC = document.currentScript.src ;
}
© Snippets Pub - 2022, under CC BY-SA 4.0
derived from:
Stack Overflow get-protocol-domain-and-port-from-url
David Calhoun Oct 17, 2014