Javascript:locationオブジェクトでURL情報を取得する

JavascriptでアクセスしているURL情報を取得する場合、
locationオブジェクトを使用すれば簡単に取得することができます。

URL、ホスト名、アンカーなど色々な情報を取得することができます。
また指定したURLに移動することもできます。

下記にlocationオブジェクトの機能や使用例をメモします。


■ locationオブジェクトの機能説明

※下記URLでアクセスした場合
「http://www.hoge.com/location/index.html?aaa=100#test」


「location.href」

現在アクセスしているURLを取得します。
また、指定したURLに遷移します。

・URLを取得

var url = location.href;
alert(url);

【実行結果】

http://www.hoge.com/location/index.html?aaa=100#test

・指定したURLに遷移

location.href = 'http://google.co.jp';

指定したURLに遷移します。


「location.host」
「location.hostname」

現在アクセスしているホスト情報を取得します。

・ホスト情報を取得(host)

var host = location.host;
alert(host);

【実行結果】

www.hoge.com

・ホスト情報を取得(hostname)

var hostname = location.hostname;
alert(hostname);

【実行結果】

www.hoge.com

「location.hash」

現在アクセスしているアンカーを取得します。
また、指定したアンカーに移動します。

・アンカーを取得

var hash = location.hash;
alert(hash);

【実行結果】

#test

「location.port」

現在アクセスしているポート番号を取得します。


「location.protocol」

現在アクセスしているプロトコルを取得します。

var protocol = location.protocol;
alert(protocol);

【実行結果】

http:

「location.pathname」

現在アクセスしているパス情報を取得します。

var pathname = location.pathname;
alert(pathname);

【実行結果】

/location/index.html

「location.search」

現在アクセスしているパラメータ情報を取得します。

var parameter = location.search;
alert(parameter);

【実行結果】

?aaa=100

  • このエントリーをはてなブックマークに追加

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です