iframeを使って別ページを読み込んだ際に、そのiframeのスクロール位置をiframe外から制御したいということがあったので、制御できるかどうか試してみます。
サンプルコード
iframeで別ページを読み込みます。
<iframe id="iframe" src="child.html" frameborder="0"></iframe>
iframeの中身のwindowオブジェクトはcontentWindowプロパティで取得できるようです。
window.addEventListener('load', function() {
const iframe = document.getElementById('iframe');
const iframeWindow = iframe.contentWindow;
iframeWindow.scrollTo({
top: 400,
behavior: "smooth"
});
});
これでiframe内のスクロール位置を変更できました。
iframeのスクロール位置を変更するデモページ
jQueryの場合、contents()でiframe内のdocumentを取得できます。
$(window).on('load', function() {
$('#iframe').contents().find('html, body').animate({
scrollTop: 400
}, 1000);
});
注意点として、iframeで読み込んでいるページのドメインが異なる場合、アクセスできません。
別ドメインのiframeの場合のデモページ(VanillaJS)
別ドメインのiframeの場合のデモページ(jQuery)
コメントが承認されるまで時間がかかります。