戻る

戻るボタンを実行した場合、元のスクロール位置に戻す処理[簡易的処理]
戻るボタンを実行した場合に前回のスクロール位置で表示する処理

厳密な判定処理ではないでしょうが、現在のページから開いたページから戻ってきた場合
元の上端の位置で開き直したい場合、下記の処理をすることで
元の位置にスクロールをしてページを開くことができます。





[サンプル]
copy
let nextUrlPath = "/test.html";
const btn = document.getElementById("btn");
btn.addEventListener("click", () => 
{
	saveAndNextPage(nextUrlPath);
});
function saveAndNextPage(nextPath)
{
	let x = window.scrollX;
	let y = window.scrollY;
	sessionStorage.setItem('x', x);
	sessionStorage.setItem('y', y);
	//alert("x:"+x+" y:"+y);
	sessionStorage.setItem('nextPath', nextUrlPath);
	window.location.href = nextUrlPath;
}
window.addEventListener('pageshow', (event) => 
{
	if (event.persisted) 
	{
		console.log('this page recovery from bfcache. (back・forward)');
		judgeURL();
	} 
	else 
	{
		const entries = performance.getEntriesByType('navigation');
		if (entries.length > 0) 
		{
			const navType = entries[0].type;
			if (navType === 'back_forward') 
			{
				console.log('tap back or forward button. (except bfcache)');
				judgeURL();
			} 
			else if (navType === 'reload') 
			{
				console.log('reload page');
			} 
			else if (navType === 'navigate') 
			{
				console.log('normal navigation');
			}
		}
	}
});
function judgeURL()
{
	const nextPath = sessionStorage.getItem('nextPath') ?? "";
	if (nextPath) 
	{
		const x = sessionStorage.getItem('x') ?? 0;
		const y = sessionStorage.getItem('y') ?? 0;
		window.scrollTo(x, y);
	}
}

let x = window.scrollX;
let y = window.scrollY;
scrollXとscrollYプロパティを使用して現在開いているページの座標を取得します。

sessionStorage.setItem('nextPath', nextUrlPath);
sessionStorageに開きたいページを保存しておきます。

window.location.href = nextUrlPath;
次のページを開きます。(このサンプルではtest.htmlを開きます。)
開いたさきのページで、
ブラウザの戻るボタン
もしくは
window.history.back();
により、ページに戻ったとします。

window.addEventListener('pageshow', (event) =>
上記イベントにより戻った場合の判定処理ができます。

if (event.persisted)
ページがbfcacheから復元したケースに実行されます。(戻る・進む)
この判定に一致した場合、judgeURL関数を実行しています。

if (navType === 'back_forward')
戻る・進むボタンが押されました (bfcache以外)
この判定に一致した場合、judgeURL関数を実行しています。

const nextPath = sessionStorage.getItem('nextPath') ?? "";
セッションストレージに保存したデータを取得します。

if (nextPath)
正しく取得できた場合はスクロール位置の処理を実行します。

const x = sessionStorage.getItem('x') ?? 0;
const y = sessionStorage.getItem('y') ?? 0;
window.scrollTo(x, y);
sessionStorage.getItem('x')から保存しておいたx座標を取得し、y座標も同様に取得します。
scrollToメソッドを使用することで上端の座標位置にスクロールすることができます。

document.referrer は「直前に開いていたページ」ではなく「最初に遷移してきたページ」を返すことが多く、
ブラウザや履歴の状況によっては期待通りに動きません。
複雑な遷移(複数タブ、検索からの流入、リロード、SPA遷移など)が混じると破綻しがちです。
戻り復元の制御は自分で明示的に記録・復元する(sessionStoragee)方式の方が安全です。


戻る


著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームペーよびアプリ利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。