Javascript get current domain

How to get the domain name from a URL in JavaScript

In this tutorial I’ll show you how to get the domain name from a URL using JavaScript. Many tutorials around the web use complicated regular expression to achieve this task but it can be done in a more straight forward way using the URL API.

Note – if you are looking to get the domain name from the current page being viewed in a browser you can simply use window.location.hostname . This tutorial is for those that need to extract a domain name from a URL that’s part of a data source.

First let’s create a string with our URL:

const url = "https://www.example.com/blog?search=hello&world";Code language: JavaScript (javascript)

If this isn’t a correctly formatted complete URL e.g example.com/blog an error is thrown.

Next create a URL object using the new URL() constructor:

let domain = (new URL(url));Code language: JavaScript (javascript)

The URL() constructor allows us to create a URL object from a string similar to the object created when using window.location . With the object created we can access the hostname property which returns a string containing the domain name:

domain = domain.hostname; console.log(domain); //www.example.comCode language: JavaScript (javascript)

If you require a naked domain the www can be removed using the replace() method.

domain = domain.hostname.replace('www.',''); console.log(domain); //example.comCode language: JavaScript (javascript)

Some additional properties you can access using the URL constructor include:

const pathname = domain.pathname; console.log(pathname); // blog const protocol = domain.protocol; console.log(protocol); // https const search = domain.search; console.log(search); // ?search=hello&worldCode language: JavaScript (javascript)

The URL API is currently supported by all modern browsers with a polyfill available for IE.

That’s all for this tutorial hopefully you found it helpful. While you’re here be sure checkout our other practical Javascript tutorials and consider signing up to our email newsletter to get updates when new tutorials are published.

Источник

How to Get the Current Domain Name in JavaScript

This tutorial will show you how to get the current domain name in JavaScript (and more).

Suppose you’re building a website or a web application and, for one reason or another, you need to get the current domain name in JavaScript.

What’s the best way to do that?

To get the value of the current domain name in JavaScript, reference the hostname property of the window.location object.

In this tutorial, I will show you exactly how to do that—and give you some of my best tips on how to work with it.

How It Works

If you opened up your browser’s console right now and referenced the following object:

// The hostname property of the window.location object window.location.hostname

You would see that the hostname of this page is makersaid.com .

Were this domain name prefixed with “www,” the value of the hostname would have been www.makersaid.com .

The value of window.location.hostname is a USVString, which means a sequence of Unicode scalar values. (In our JavaScript code, we treat USVStrings as regular strings.)

Ways to Use It

Store It for Subsequent Use

Nine times out of ten, you will only need to reference the string and store it for future use in a constant or variable:

// Store value of hostname in a constant const domainName = window.location.hostname // Store value of hostname in a variable var domainName = window.location.hostname

Split It Into an Array

However, you can also split the string into an array at every dot (.) with the String.prototype.split() method:

// Split value of hostname into an array window.location.hostname.split('.')

Once again, if you fired up the browser’s console and gave this statement a spin, you’d get an array consisting of two values: [‘makersaid’, ‘com’] .

Were this domain name prefixed with “www,” the array would have consisted of three values: [‘www’, ‘makersaid’, ‘com’] .

Splitting the hostname property into data elements in an array can be useful if you’re developing business logic for multiple domain names and need clean values to determine the current domain name.

Clean It From a Prefix

You can even go further and check if your hostname has a prefix, such as ‘www,’ and erase that prefix from the array by using the Array.shift() method:

// Clean domain name value from 'www' or other prefix function cleanDomain(removeValue)  var domainName = window.location.hostname.split('.'); if (domainName.includes(removeValue))   domainName.shift();  console.log(domainName);  > else   console.log(domainName);  > > cleanDomain('www');

In Conclusion

Thank you for reading this far and I hope this tutorial helped you get the job done.

The window object in JavaScript has a number of useful read-only properties that can be useful in your daily work. I recommend you experiment with them and learn them, as using them can make your code faster and leaner.

Leave a comment Cancel reply

  • How to Wait for an Element to Exist in JavaScript July 13, 2023
  • How to Check If a Function Exists in JavaScript July 13, 2023
  • How to Remove Numbers From a String With RegEx July 13, 2023
  • How to Check If a String Is a Number in JavaScript July 13, 2023
  • How to Insert a Variable Into a String in PHP July 12, 2023

We publish growth advice, technology how-to’s, and reviews of the best products for entrepreneurs, creators, and creatives who want to write their own story.

Maker’s Aid is a participant in the Amazon Associates, Impact.com, and ShareASale affiliate advertising programs.

These programs provide means for websites to earn commissions by linking to products. As a member, we earn commissions on qualified purchases made through our links.

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Document: domain property

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The domain property of the Document interface gets/sets the domain portion of the origin of the current document, as used by the same-origin policy.

Value

Exceptions

Use of this feature was blocked by a Permissions Policy.

Examples

Getting the domain

For code running at the URL https://developer.mozilla.org/en-US/docs/Web , this example would set currentDomain to the string » developer.mozilla.org «.

const currentDomain = document.domain; 

The getter for this property returns the domain portion of the current document’s origin. In most cases, this will be the hostname portion of the document’s URL. However, there are some exceptions:

  • If the page has an opaque origin, e.g. for a page with a data URL, then it will return the empty string.
  • If the document.domain setter has been used, then it will return the value that was set.

Although the getter is not dangerous in the same way that the setter is, it is likely simpler and more useful to use the Location.hostname property instead. Then you can avoid document.domain entirely:

const currentHostname = location.hostname; 

For the URL https://developer.mozilla.org/en-US/docs/Web , currentHostname is also the string » developer.mozilla.org «. Other alternatives that provide slightly different information are Location.host , which includes the port, and origin , which provides the full origin.

Setting the domain

The setter for this property can be used to change a page’s origin, and thus modify how certain security checks are performed. It can only be set to the same or a parent domain. For example, if https://a.example.com and https://b.example.com both use

then they have both modified their origin to have the same domain, and they can now access each other’s DOM directly—despite being cross-origin, which would normally prevent such access.

Note that setting document.domain to its current value is not a no-op. It still changes the origin. For example, if one page sets

then it will be counted as cross-origin from any other normally-same-origin pages that have not done the same thing.

Deprecation

The document.domain setter is deprecated. It undermines the security protections provided by the same origin policy, and complicates the origin model in browsers, leading to interoperability problems and security bugs.

Attempting to set document.domain is dangerous. It opens up full access to a page’s DOM from all subdomains, which is likely not what is intended. It also removes the port component from the origin, so now your page can be accessed by other pages with the same IP address or same host component, even on a different port.

This is especially insecure on shared hosting. For example, another shared hosting customer is able to host a site at the same IP address but on a different port, then setting document.domain will remove the same-origin protection that normally protects you from that other customer’s site accessing your site’s data.

Similar problems occur with shared hosting sites that give each customer a different subdomain. If a site sets document.domain , any other customer on a different subdomain can now do the same thing, and start accessing the data of the original site.

Instead of using document.domain to facilitate cross-origin communication, you should use Window.postMessage to send an asynchronous message to the other origin. This controlled access via message-passing is much more secure than the blanket exposure of all data caused by document.domain .

Failures

The setter will throw a » SecurityError » DOMException in several cases:

  • The document-domainPermissions-Policy is disabled.
  • The document is inside a sandboxed .
  • The document has no browsing context.
  • The document’s effective domain is null .
  • The given value is neither the same as the page’s current hostname, nor a parent domain of it.

As an example of this last failure case, trying to set document.domain to «example.org» when on https://example.com/ will throw.

Additionally, as part of its deprecation, it will do nothing when combined with certain modern isolation features:

  • If used on a cross-origin isolated page, i.e. one that uses the appropriate values for the Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy HTTP headers
  • If used on an origin-isolated page, i.e. one that uses the Origin-Isolation HTTP header

Finally, setting document.domain does not change the origin used for origin-checks by some Web APIs, preventing sub-domain access via this mechanism. Affected APIs include (but are not limited to): Window.localStorage , IndexedDB_API , BroadcastChannel , SharedWorker .

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Источник

Читайте также:  Css before after url
Оцените статью