Неможливо взаємодіяти з iFrame іншого походження за допомогою Javascript, щоб отримати його розмір; єдиний спосіб зробити це - використовувати window.postMessage
разом із targetOrigin
набором для вашого домену або wildchar *
із джерела iFrame. Ви можете проксі вміст різних сайтів походження та використання srcdoc
, але це вважається хаком, і він не працюватиме з SPAs та багатьма іншими більш динамічними сторінками.
Розмір iFrame одного походження
Припустимо, у нас два iFrames одного походження, один короткої висоти та фіксованої ширини:
<!-- iframe-short.html -->
<head>
<style type="text/css">
html, body { margin: 0 }
body {
width: 300px;
}
</style>
</head>
<body>
<div>This is an iFrame</div>
<span id="val">(val)</span>
</body>
і довгий зріст iFrame:
<!-- iframe-long.html -->
<head>
<style type="text/css">
html, body { margin: 0 }
#expander {
height: 1200px;
}
</style>
</head>
<body>
<div>This is a long height iFrame Start</div>
<span id="val">(val)</span>
<div id="expander"></div>
<div>This is a long height iFrame End</div>
<span id="val">(val)</span>
</body>
Ми можемо отримати розмір iFrame для load
події, використовуючи iframe.contentWindow.document
те, що будемо надсилати до батьківського вікна за допомогою postMessage
:
<div>
<iframe id="iframe-local" src="iframe-short.html"></iframe>
</div>
<div>
<iframe id="iframe-long" src="iframe-long.html"></iframe>
</div>
<script>
function iframeLoad() {
window.top.postMessage({
iframeWidth: this.contentWindow.document.body.scrollWidth,
iframeHeight: this.contentWindow.document.body.scrollHeight,
params: {
id: this.getAttribute('id')
}
});
}
window.addEventListener('message', ({
data: {
iframeWidth,
iframeHeight,
params: {
id
} = {}
}
}) => {
// We add 6 pixels because we have "border-width: 3px" for all the iframes
if (iframeWidth) {
document.getElementById(id).style.width = `${iframeWidth + 6}px`;
}
if (iframeHeight) {
document.getElementById(id).style.height = `${iframeHeight + 6}px`;
}
}, false);
document.getElementById('iframe-local').addEventListener('load', iframeLoad);
document.getElementById('iframe-long').addEventListener('load', iframeLoad);
</script>
Ми отримаємо належну ширину та висоту для обох iFrames; ви можете перевірити його онлайн тут і подивитися скріншот тут .
Різні походження розмір плаваючого фрейма хак ( не рекомендується )
Описаний тут метод є злому, і його слід використовувати, якщо це абсолютно необхідно і немає іншого способу; він не працюватиме для більшості динамічно створених сторінок та SPA-програм. Метод отримує вихідний код HTML-сторінки за допомогою проксі-сервера для обходу політики CORS ( cors-anywhere
це простий спосіб створити простий проксі-сервер CORS і має демонстрацію в Інтернетіhttps://cors-anywhere.herokuapp.com
), після чого він вводить JS-код у цей HTML, щоб використовувати postMessage
та надсилати розмір iFrame до батьківського документа. Він навіть обробляє iFrame resize
(у поєднанні з iFramewidth: 100%
) події та розміщує розмір iFrame назад до батьківського.
patchIframeHtml
:
Функція для виправлення iFrame HTML-коду та введення спеціального Javascript, який буде використовуватися postMessage
для надсилання iFrame-розміру на батьків load
і далі resize
. Якщо для origin
параметра є значення , то HTML- <base/>
елемент буде готуватися до голови за допомогою цієї вихідної URL-адреси, таким чином, HTML-URI, як-от, /some/resource/file.ext
буде отримано належним чином за початковою URL-адресою всередині iFrame.
function patchIframeHtml(html, origin, params = {}) {
// Create a DOM parser
const parser = new DOMParser();
// Create a document parsing the HTML as "text/html"
const doc = parser.parseFromString(html, 'text/html');
// Create the script element that will be injected to the iFrame
const script = doc.createElement('script');
// Set the script code
script.textContent = `
window.addEventListener('load', () => {
// Set iFrame document "height: auto" and "overlow-y: auto",
// so to get auto height. We set "overlow-y: auto" for demontration
// and in usage it should be "overlow-y: hidden"
document.body.style.height = 'auto';
document.body.style.overflowY = 'auto';
poseResizeMessage();
});
window.addEventListener('resize', poseResizeMessage);
function poseResizeMessage() {
window.top.postMessage({
// iframeWidth: document.body.scrollWidth,
iframeHeight: document.body.scrollHeight,
// pass the params as encoded URI JSON string
// and decode them back inside iFrame
params: JSON.parse(decodeURIComponent('${encodeURIComponent(JSON.stringify(params))}'))
}, '*');
}
`;
// Append the custom script element to the iFrame body
doc.body.appendChild(script);
// If we have an origin URL,
// create a base tag using that origin
// and prepend it to the head
if (origin) {
const base = doc.createElement('base');
base.setAttribute('href', origin);
doc.head.prepend(base);
}
// Return the document altered HTML that contains the injected script
return doc.documentElement.outerHTML;
}
getIframeHtml
:
Функція для отримання HTML-сторінки сторінки в обхід CORS за допомогою проксі, якщо встановлено useProxy
параметр. Можуть бути додаткові параметри, які передаватимуться postMessage
при передачі даних про розмір.
function getIframeHtml(url, useProxy = false, params = {}) {
return new Promise(resolve => {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
// If we use a proxy,
// set the origin so it will be placed on a base tag inside iFrame head
let origin = useProxy && (new URL(url)).origin;
const patchedHtml = patchIframeHtml(xhr.responseText, origin, params);
resolve(patchedHtml);
}
}
// Use cors-anywhere proxy if useProxy is set
xhr.open('GET', useProxy ? `https://cors-anywhere.herokuapp.com/${url}` : url, true);
xhr.send();
});
}
Функція обробника подій повідомлення точно така ж, як і в "Одне і те ж розмір iFrame" .
Тепер ми можемо завантажити домен перехресного походження всередині iFrame з інжектованим нашим JS-кодом:
<!-- It's important that the iFrame must have a 100% width
for the resize event to work -->
<iframe id="iframe-cross" style="width: 100%"></iframe>
<script>
window.addEventListener('DOMContentLoaded', async () => {
const crossDomainHtml = await getIframeHtml(
'https://en.wikipedia.org/wiki/HTML', true /* useProxy */, { id: 'iframe-cross' }
);
// We use srcdoc attribute to set the iFrame HTML instead of a src URL
document.getElementById('iframe-cross').setAttribute('srcdoc', crossDomainHtml);
});
</script>
І ми отримаємо iFrame за розміром до його вмісту на повний зріст без вертикальної прокрутки, навіть використовуючи overflow-y: auto
для корпусу iFrame ( так і повинно бути, overflow-y: hidden
щоб у нас не було мерехтіння смуги прокрутки за розміром ).
Ви можете перевірити його онлайн тут .
Знову помітити, що це хакер, і цього слід уникати ; ми не можемо отримати доступ до документа iFrame Cross-Origin і не вводити будь-які речі.