戻るボタンを実行した場合、元のスクロール位置に戻す処理[簡易的処理] |
戻るボタンを実行した場合に前回のスクロール位置で表示する処理 |
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);
}
}
| ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。 ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、 または公開したりすることはできません。 当方は、ホームペーよびアプリ利用したいかなる理由によっての障害等が発生しても、 その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について 一切の責任を負わないものとします。 |