SYNCERのロゴ
アイキャッチ画像

Location.replace() - ロケーションを置換する

replace()は、Locationのメソッドです。新しいロケーションに遷移させます。ただし、履歴エントリーは追加されずに、現在の履歴エントリーと置き換わります。そのため、遷移前のページに戻ることはできません。

概要

名前
replace
所属
Location
IDL
[Unforgeable] void replace(USVString url);
仕様書
https://html.spec.whatwg.org/multipage/history.html#dom-location-replace

説明

引数(url)には、対象のアドレスを指定します。

チュートリアル

Location.replace()は現在のロケーションを、新しいロケーションに置き換えるメソッドです。置換なので履歴エントリーが追加されません。

// 1つ前のアドレス
// "https://syncer.jp/0.html"

// 現在のアドレス
// "https://syncer.jp/1.html"

// メソッドを実行
location.replace( "https://syncer.jp/2.html" ) ;	// "https://syncer.jp/2.html"に遷移

// ブラウザバックをすると…
// "https://syncer.jp/2.html"→"https://syncer.jp/0.html"に戻る

デモ

Location.replace()のデモです。履歴エントリーが現在のものと置き換わるため、遷移後、ヒストリーバックで元のページに戻ることはできません。assign()と比べてみて下さい。

<!DOCTYPE html>
<html>
<body>
<button id="run1">replace()</button>
<button id="run2">assign()</button>
<script>
document.getElementById( "run1" ).onclick = function () {
	location.replace( "https://example.com/" ) ;
}

document.getElementById( "run2" ).onclick = function () {
	location.assign( "https://example.com/" ) ;
}
</script>
</body>
</html>

サポート状況

ChromeFirefoxSafariEdgeIEOperaiOS SafariAndroid
  • Twitterでシェア
  • Facebookでシェア
  • Google+でシェア
  • はてなブックマークでシェア
  • pocketに保存
  • LINEでシェア
更新履歴
2017年10月8日 (日)
コンテンツを公開しました。