pasaribu
pasaribu

Reputation: 95

How to access host from chrome extension

I'm looking for a way to read the current tab's host (not just hostname).

I can read the url, but can't seem to find a reliable regex to extract out the host.

I can get the host from the window.location object, but I can't find a way to access that data from the extension.

Upvotes: 2

Views: 540

Answers (1)

Rob W
Rob W

Reputation: 348962

Given an URL, you can use the URL constructor to parse it and extract the parsed URL components. For instance:

// Just an example, there are many ways to get a URL in an extension...
var url = 'http://example.com:1234/test?foo=bar#hello=world';
var parsedUrl = new URL(url);
console.log(parsedUrl.host);

// Or if you want a one-liner:
console.log(new URL(url).host);
Open the JavaScript console, and you'll see "example.com:1234" (2x).

Upvotes: 4

Related Questions