2

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.

Community
  • 1
  • 1
Pasaribu
  • 95
  • 6

1 Answers1

4

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).
Rob W
  • 341,306
  • 83
  • 791
  • 678