【初心者向け】JavaScript URLの取得と操作 - locationオブジェクト入門
JavaScriptのlocationオブジェクトを使ってURLを取得・操作する方法を初心者向けに解説。URLの各部分の取得からページ遷移の実装まで、実用的なサンプルコードを紹介します。
【初心者向け】JavaScript URLの取得と操作 - locationオブジェクト入門
みなさん、Webサイトを作っていて、こんなことを思ったことはありませんか?
「現在のURLを取得したい」 「ページを自動的に移動させたい」
Webサイトを作っていると、現在のURLを取得したり、ページを移動させたりする必要がありますよね。 例えば、現在のページのURLを取得してシェアボタンを作ったり、条件に応じて別のページにリダイレクトしたりする場面があります。
でも大丈夫です!
この記事では、JavaScriptのlocationオブジェクトを使ってURLを取得・操作する方法を初心者向けに詳しく解説します。 基本的な使い方から実用的なサンプルコードまで、実際に使えるレベルまで理解できるように説明していきます。
一緒にURL操作をマスターしましょう!
locationオブジェクトって何?
基本的な役割
locationオブジェクトは、現在のページのURLに関する情報を提供するJavaScriptの組み込みオブジェクトです。
URLの各部分を個別に取得したり、ページの移動を行ったりすることができます。 簡単に言うと、ブラウザのアドレスバーの情報を扱う道具なんです。
// 現在のURLを取得console.log(location.href);// 例: https://example.com/page?id=123#section1
// ホスト名を取得console.log(location.hostname);// 例: example.com
この例では、現在のページの完全なURLとホスト名を表示しています。
location.href
で完全なURL、location.hostname
でドメイン名が取得できます。
とてもシンプルで使いやすいですよね!
URLの構造を理解しよう
URLの各部分の意味
まず、URLの基本的な構造を理解しましょう。
https://example.com:8080/path/to/page?id=123&name=test#section1
| | | | | |
| | | | | └─ hash(フラグメント)
| | | | └─ search(クエリ文字列)
| | | └─ pathname(パス)
| | └─ port(ポート)
| └─ hostname(ホスト名)
└─ protocol(プロトコル)
この図を見ると、URLがいくつかの部分に分かれているのがわかります。
それぞれの部分には意味があり、locationオブジェクトで個別に取得できます。 この構造を覚えておくと、URLを扱うときにとても便利ですよ。
locationオブジェクトの便利な機能
基本的なプロパティを使ってみよう
locationオブジェクトの主要なプロパティをご紹介します。
// URL全体を取得console.log(location.href);// 例: https://example.com/page?id=123#section1
// プロトコルを取得console.log(location.protocol);// 例: https:
// ホスト名を取得console.log(location.hostname);// 例: example.com
// ポート番号を取得console.log(location.port);// 例: 8080(デフォルトポートの場合は空文字)
// ホスト名+ポート番号を取得console.log(location.host);// 例: example.com:8080
// パスを取得console.log(location.pathname);// 例: /page
// クエリ文字列を取得console.log(location.search);// 例: ?id=123&name=test
// フラグメントを取得console.log(location.hash);// 例: #section1
各プロパティは、URLの特定の部分を簡単に取得できます。
href
は完全なURL、hostname
はドメイン名、pathname
はパス部分を返します。
search
はクエリパラメータ、hash
はページ内リンクの部分を取得できます。
実用的な情報表示関数
URLの情報をまとめて表示する便利な関数をご紹介します。
function displayUrlInfo() { const urlInfo = { fullUrl: location.href, protocol: location.protocol, hostname: location.hostname, port: location.port || 'デフォルト', pathname: location.pathname, search: location.search || 'なし', hash: location.hash || 'なし' }; console.log('現在のURL情報:'); for (const [key, value] of Object.entries(urlInfo)) { console.log(`${key}: ${value}`); }}
displayUrlInfo();
この関数では、URLのすべての情報をオブジェクトにまとめて表示しています。
||
演算子を使って、空の場合は「デフォルト」や「なし」と表示するようにしています。
デバッグ時や開発中に現在のURL情報を確認したいときに便利です。
クエリパラメータを簡単に取得しよう
URLSearchParamsを使う方法(推奨)
クエリパラメータを簡単に取得する方法をご紹介します。
function getQueryParams() { const params = new URLSearchParams(location.search); const queryParams = {}; for (const [key, value] of params.entries()) { queryParams[key] = value; } return queryParams;}
// 使用例const params = getQueryParams();console.log(params);// 例: { id: '123', name: 'test' }
// 特定のパラメータを取得function getParam(name) { const params = new URLSearchParams(location.search); return params.get(name);}
console.log(getParam('id')); // 123console.log(getParam('name')); // test
URLSearchParams
は、クエリパラメータを扱うための専用クラスです。
?id=123&name=test
のような文字列を自動的に解析してくれます。
特定のパラメータだけが欲しい場合は、get()
メソッドを使うと簡単です。
自分でパースする方法
URLSearchParamsが使えない古いブラウザ向けの方法もご紹介します。
function parseQueryString(queryString) { const params = {}; if (queryString) { // 最初の'?'を除去 const cleanQuery = queryString.startsWith('?') ? queryString.slice(1) : queryString; // '&'で分割 const pairs = cleanQuery.split('&'); pairs.forEach(pair => { const [key, value] = pair.split('='); if (key) { params[decodeURIComponent(key)] = decodeURIComponent(value || ''); } }); } return params;}
// 使用例const params = parseQueryString(location.search);console.log(params);
この方法では、クエリ文字列を手動で解析しています。 まず「?」を取り除き、「&」で分割して、各パラメータを「=」で分けています。
decodeURIComponent()
を使って、URLエンコードされた文字を正しく復元しています。
ページ遷移を実装してみよう
基本的な遷移方法
JavaScriptでページを移動させる方法をご紹介します。
// 現在のページを置き換えるlocation.href = 'https://example.com/new-page';
// 同じ効果location.assign('https://example.com/new-page');
// 現在のページを履歴から削除して置き換えるlocation.replace('https://example.com/new-page');
// ページをリロードlocation.reload();
location.href
に新しいURLを代入するだけで、ページを移動できます。
assign()
メソッドも同じ動作をします。
replace()
は、現在のページを履歴から削除してから移動します。
ユーザーが「戻る」ボタンを押しても元のページに戻れなくなります。
条件に応じたリダイレクト
特定の条件でページを自動的に移動させる例をご紹介します。
function conditionalRedirect() { const userAgent = navigator.userAgent; const currentPath = location.pathname; // モバイルデバイスの場合 if (/Mobile|Android|iPhone|iPad/.test(userAgent)) { if (!currentPath.startsWith('/mobile/')) { location.href = '/mobile' + currentPath; } } // HTTPSでない場合はHTTPSにリダイレクト if (location.protocol !== 'https:' && location.hostname !== 'localhost') { location.href = 'https:' + location.href.substring(location.protocol.length); }}
// ページ読み込み時に実行conditionalRedirect();
この関数では、デバイスの種類やプロトコルをチェックして、必要に応じてリダイレクトを行います。
モバイルデバイスの場合は専用のパスに、HTTPの場合はHTTPSに自動的に移動します。 セキュリティやユーザビリティを向上させる実用的なテクニックです。
カウントダウン付きリダイレクト
ユーザーに移動を予告してからリダイレクトする方法をご紹介します。
function delayedRedirect(url, seconds) { let countdown = seconds; const countdownElement = document.getElementById('countdown'); const timer = setInterval(() => { if (countdownElement) { countdownElement.textContent = `${countdown}秒後にリダイレクトします...`; } countdown--; if (countdown < 0) { clearInterval(timer); location.href = url; } }, 1000);}
// 使用例// delayedRedirect('https://example.com', 5);
この関数では、指定した秒数をカウントダウンしながら、最後にリダイレクトを実行します。 ユーザーに移動することを事前に知らせることができます。
フォーム送信後の完了ページなどでよく使われる手法です。
実用的なサンプルを作ってみよう
パンくずリストの自動生成
現在のURLからパンくずリストを自動生成する関数をご紹介します。
function createBreadcrumbs() { const pathSegments = location.pathname.split('/').filter(segment => segment); const breadcrumbs = []; // ホームリンク breadcrumbs.push({ name: 'ホーム', url: '/' }); // パスの各セグメント let currentPath = ''; pathSegments.forEach(segment => { currentPath += '/' + segment; breadcrumbs.push({ name: segment.charAt(0).toUpperCase() + segment.slice(1), url: currentPath }); }); return breadcrumbs;}
function displayBreadcrumbs() { const breadcrumbs = createBreadcrumbs(); const breadcrumbHtml = breadcrumbs.map((crumb, index) => { const isLast = index === breadcrumbs.length - 1; if (isLast) { return `<span class="current">${crumb.name}</span>`; } else { return `<a href="${crumb.url}">${crumb.name}</a>`; } }).join(' > '); const breadcrumbContainer = document.getElementById('breadcrumbs'); if (breadcrumbContainer) { breadcrumbContainer.innerHTML = breadcrumbHtml; }}
この関数では、現在のパスを「/」で分割して、各セグメントからパンくずリストを作成します。
最初にホームリンクを追加し、その後パスの各部分をリンクとして追加します。 最後の項目は現在のページなので、リンクではなくテキストとして表示します。
シェアボタンの実装
現在のページをSNSでシェアするボタンを作る関数をご紹介します。
function createShareButtons() { const currentUrl = encodeURIComponent(location.href); const pageTitle = encodeURIComponent(document.title); const shareUrls = { twitter: `https://twitter.com/intent/tweet?url=${currentUrl}&text=${pageTitle}`, facebook: `https://www.facebook.com/sharer/sharer.php?u=${currentUrl}`, line: `https://social-plugins.line.me/lineit/share?url=${currentUrl}` }; return shareUrls;}
function displayShareButtons() { const shareUrls = createShareButtons(); const shareContainer = document.getElementById('share-buttons'); if (shareContainer) { shareContainer.innerHTML = ` <div class="share-buttons"> <a href="${shareUrls.twitter}" target="_blank" class="share-button twitter"> Twitter でシェア </a> <a href="${shareUrls.facebook}" target="_blank" class="share-button facebook"> Facebook でシェア </a> <a href="${shareUrls.line}" target="_blank" class="share-button line"> LINE でシェア </a> </div> `; }}
この関数では、現在のURLとページタイトルを取得して、各SNSのシェア用URLを生成します。
encodeURIComponent()
を使って、URLに含まれる特殊文字を適切にエンコードしています。
実際のWebサイトでよく見かけるシェアボタンを簡単に実装できます。
URLをクリップボードにコピー
現在のURLをクリップボードにコピーする機能をご紹介します。
function copyUrlToClipboard() { const currentUrl = location.href; navigator.clipboard.writeText(currentUrl).then(() => { alert('URLをクリップボードにコピーしました!'); }).catch(err => { console.error('クリップボードへのコピーに失敗:', err); // フォールバック処理 const textArea = document.createElement('textarea'); textArea.value = currentUrl; document.body.appendChild(textArea); textArea.select(); document.execCommand('copy'); document.body.removeChild(textArea); alert('URLをクリップボードにコピーしました!'); });}
この関数では、まず新しいnavigator.clipboard
APIを使ってコピーを試みます。
失敗した場合は、古い方法(document.execCommand
)でコピーします。
このように、新旧の方法を組み合わせることで、幅広いブラウザで動作する機能を作ることができます。
セキュリティも考慮しよう
安全なリダイレクト
リダイレクト機能を実装するときは、セキュリティも考慮する必要があります。
function safeRedirect(url) { // 許可されたドメインのリスト const allowedDomains = ['example.com', 'subdomain.example.com']; try { const urlObject = new URL(url); // 同じドメインまたは許可されたドメインのみ許可 if (urlObject.hostname === location.hostname || allowedDomains.includes(urlObject.hostname)) { location.href = url; } else { console.error('安全でないリダイレクト先:', url); alert('無効なリダイレクト先です'); } } catch (error) { console.error('無効なURL:', url); alert('無効なURLです'); }}
この関数では、リダイレクト先のドメインをチェックして、許可されたドメインのみリダイレクトを許可します。 悪意のあるサイトへの自動リダイレクトを防ぐことができます。
XSS攻撃の対策
URLに含まれる危険なスクリプトを除去する方法をご紹介します。
function sanitizeUrl(url) { // JavaScriptスキームを除去 if (url.toLowerCase().startsWith('javascript:')) { return '#'; } // data:スキームを除去 if (url.toLowerCase().startsWith('data:')) { return '#'; } return url;}
function createSafeLink(url, text) { const safeUrl = sanitizeUrl(url); return `<a href="${safeUrl}" target="_blank" rel="noopener noreferrer">${text}</a>`;}
この関数では、危険なスキーム(javascript:
やdata:
)を含むURLを無害化します。
また、rel="noopener noreferrer"
を追加して、新しいタブでのセキュリティも向上させています。
History APIと組み合わせてみよう
SPA風のページ遷移
History APIと組み合わせて、ページをリロードせずにURLを変更する方法をご紹介します。
function navigateToPage(path, state = {}) { // 履歴にエントリを追加 history.pushState(state, '', path); // ページ内容を更新 updatePageContent(path); updatePageTitle();}
function updatePageContent(path) { const content = document.getElementById('content'); // パスに基づいてコンテンツを更新 switch (path) { case '/': content.innerHTML = '<h1>ホームページ</h1>'; break; case '/about': content.innerHTML = '<h1>会社概要</h1>'; break; case '/contact': content.innerHTML = '<h1>お問い合わせ</h1>'; break; default: content.innerHTML = '<h1>ページが見つかりません</h1>'; }}
// ブラウザの戻る/進むボタンの処理window.addEventListener('popstate', (event) => { updatePageContent(location.pathname); updatePageTitle();});
この実装では、ページをリロードせずにURLとコンテンツを動的に変更します。 SPAのような滑らかなユーザー体験を提供できます。
動的なページタイトル更新
URLに応じてページタイトルを自動更新する関数をご紹介します。
function updatePageTitle() { const pathSegments = location.pathname.split('/').filter(segment => segment); const queryParams = new URLSearchParams(location.search); let title = 'マイサイト'; if (pathSegments.length > 0) { const lastSegment = pathSegments[pathSegments.length - 1]; title = lastSegment.charAt(0).toUpperCase() + lastSegment.slice(1) + ' - マイサイト'; } // クエリパラメータに基づいてタイトルを調整 const category = queryParams.get('category'); if (category) { title = `${category} - ${title}`; } document.title = title;}
// ページ読み込み時とhistory変更時に実行updatePageTitle();window.addEventListener('popstate', updatePageTitle);
この関数では、現在のパスやクエリパラメータに基づいて、動的にページタイトルを生成します。 SEOにも有効で、ユーザビリティも向上します。
まとめ:URL操作をマスターしよう
JavaScriptのlocationオブジェクトを使ったURL操作について、基礎から実践まで詳しく解説しました。
重要なポイントをまとめると以下の通りです。
- locationオブジェクトで現在のURLの各部分を取得
- URLSearchParamsでクエリパラメータを効率的に処理
- 適切なセキュリティ対策を実装
- History APIとの連携でSPA風の履歴管理
実践での心がけ:
URL操作を活用する際は、以下を意識しましょう。
- URLの解析にはURLクラスを活用
- セキュリティを常に考慮したリダイレクト処理
- パフォーマンスを意識したキャッシュ実装
- ユーザビリティを向上させるUI/UX設計
これらの知識を活用することで、ユーザーフレンドリーで安全なWebアプリケーションを構築できるようになります。
URL操作は現代のWeb開発において基本的かつ重要なスキルです。 今回学んだテクニックを使って、より便利で使いやすいWebサイトを作ってみませんか?
ぜひ実際のプロジェクトで活用してみてください!