Locationオブジェクト
Location オブジェクト
Location オブジェクトは、現在の URL に関する情報を含みます。
Location オブジェクトは window オブジェクトの一部であり、window.location.xxx形式の関連プロパティを使用してアクセスできます。
注意:Location オブジェクトに適用される公開標準はありませんが、すべてのブラウザーがこのオブジェクトをサポートしています。
Location オブジェクトのプロパティ
| プロパティ | 説明 |
|---|---|
| hash | URL のアンカー部分を返します。 |
| host | URL のホスト名とポートを返します。 |
| hostname | URL のホスト名を返します。 |
| href | 完全な URL を返します。 |
| pathname | URL のパス名を返します。 |
| port | URL サーバーが使用するポート番号を返します。 |
| protocol | URL のプロトコルを返します。 |
| search | URL のクエリ部分を返します。 |
例
// a タグを作成し、href 属性を設定します
var url = document.createElement('a');
url.href = 'https://www.example.com/?s=python#test';
console.log(url.href); // https://www.example.com/?s=python
console.log(url.protocol); // https:
console.log(url.host); // www.example.com
console.log(url.hostname); // www.example.com
console.log(url.port); // (出力は空 - https のデフォルトポートは 443)
console.log(url.pathname); // /
console.log(url.search); // en-US/search
console.log(url.hash); // #test
console.log(url.origin); // https://www.example.com
var url = document.createElement('a');
url.href = 'https://www.example.com/?s=python#test';
console.log(url.href); // https://www.example.com/?s=python
console.log(url.protocol); // https:
console.log(url.host); // www.example.com
console.log(url.hostname); // www.example.com
console.log(url.port); // (出力は空 - https のデフォルトポートは 443)
console.log(url.pathname); // /
console.log(url.search); // en-US/search
console.log(url.hash); // #test
console.log(url.origin); // https://www.example.com
テスト結果は次のとおりです:

Location オブジェクトのメソッド
| メソッド | 説明 |
|---|---|
| assign() | 新しいドキュメントを読み込みます |
| reload() | 現在のドキュメントを再読み込みします |
| replace() | 新しいドキュメントで現在のドキュメントを置き換えます |