Iframe error event

I have an that other sites can include so their users can POST a form back to my site. I'd like to handle gracefully the cases where my site is down or my server can't serve the <...

I have an <iframe> that other sites can include so their users can POST a form back to my site. I’d like to handle gracefully the cases where my site is down or my server can’t serve the <iframe> contents (that is, a response timeout or a 4xx or 5xx error). I tried adding an onError to the <iframe> object, but that didn’t seem to do anything:

showIFrame = function() {
  var iframe = document.createElement('iframe');
  iframe.id = 'myIFrame';
  iframe.src = 'http://myserver.com/someURLThatFailsToLoad';
  iframe.onError = iframe.onerror = myHandler;
  document.body.appendChild(iframe);
};

myHandler = function(error) {
  document.getElementById('myIFrame').style.display = 'none';
  console.error('Error loading iframe contents: ' + error);
  return true;
};

If my server returns a 404 I just get the contents of the not-found page in my <iframe>. In fact, that error handler isn’t ever triggered. Is there a way to make this work?

(I’m currently testing in Chrome, but I’d like it to also work for FF and IE >= 7.)

asked Sep 13, 2010 at 23:11

James A. Rosen's user avatar

James A. RosenJames A. Rosen

63.5k61 gold badges178 silver badges261 bronze badges

To detect whether your server is down or not, you can include an empty script file from your own domain. When the server is down, the onerror event handler will fire:

var el = document.createElement('script');
el.onerror = errorFunction;
el.src = "somebogusscript.js?" + new Date().getTime();
document.body.appendChild(el);

Note: don’t forget to add a random string to the src attribute to avoid the client using a cached version (which could stop a look at the server at all).

answered Sep 13, 2010 at 23:17

Marcel Korpel's user avatar

Marcel KorpelMarcel Korpel

21.5k6 gold badges60 silver badges80 bronze badges

5

One technique is to set a JavaScript timeout when you make the request. If your timeout fires before the iframe onload event, the content didn’t load. You could then set iframe.src to about:blank, delete, or reuse the iframe.

answered Mar 29, 2012 at 8:51

Sam Watkins's user avatar

Sam WatkinsSam Watkins

7,6413 gold badges38 silver badges38 bronze badges

I have an <iframe> that other sites can include so their users can POST a form back to my site. I’d like to handle gracefully the cases where my site is down or my server can’t serve the <iframe> contents (that is, a response timeout or a 4xx or 5xx error). I tried adding an onError to the <iframe> object, but that didn’t seem to do anything:

showIFrame = function() {
  var iframe = document.createElement('iframe');
  iframe.id = 'myIFrame';
  iframe.src = 'http://myserver.com/someURLThatFailsToLoad';
  iframe.onError = iframe.onerror = myHandler;
  document.body.appendChild(iframe);
};

myHandler = function(error) {
  document.getElementById('myIFrame').style.display = 'none';
  console.error('Error loading iframe contents: ' + error);
  return true;
};

If my server returns a 404 I just get the contents of the not-found page in my <iframe>. In fact, that error handler isn’t ever triggered. Is there a way to make this work?

(I’m currently testing in Chrome, but I’d like it to also work for FF and IE >= 7.)

asked Sep 13, 2010 at 23:11

James A. Rosen's user avatar

James A. RosenJames A. Rosen

63.5k61 gold badges178 silver badges261 bronze badges

To detect whether your server is down or not, you can include an empty script file from your own domain. When the server is down, the onerror event handler will fire:

var el = document.createElement('script');
el.onerror = errorFunction;
el.src = "somebogusscript.js?" + new Date().getTime();
document.body.appendChild(el);

Note: don’t forget to add a random string to the src attribute to avoid the client using a cached version (which could stop a look at the server at all).

answered Sep 13, 2010 at 23:17

Marcel Korpel's user avatar

Marcel KorpelMarcel Korpel

21.5k6 gold badges60 silver badges80 bronze badges

5

One technique is to set a JavaScript timeout when you make the request. If your timeout fires before the iframe onload event, the content didn’t load. You could then set iframe.src to about:blank, delete, or reuse the iframe.

answered Mar 29, 2012 at 8:51

Sam Watkins's user avatar

Sam WatkinsSam Watkins

7,6413 gold badges38 silver badges38 bronze badges

Время прочтения
11 мин

Просмотры 149K

iframe tag

Элемент iframe (сокращение от встроенного фрейма), вероятно, является одним из старейших тегов HTML и был представлен ещё в далеком 1997 году в HTML 4.01 Microsoft Internet Explorer.

Хотя все современные браузеры поддерживают данный тег, многие разработчики пишут бесконечные статьи, не советуя им пользоваться. Я считаю, что плохая репутация, которая сформировалась, около данного тега не должна мешать вам использовать его. У данного тега есть много хороших примеров применения. Кроме того, iframe не так сложно защитить, поэтому вам не придется беспокоиться о заражении компьютера вашего пользователя.

Чтобы помочь вам сформировать собственное мнение и отточить свои навыки разработчика, мы расскажем обо всем, что вам нужно знать об этом противоречивом теге.

Мы рассмотрим большинство функций, которые предоставляет элемент iframe, и поговорим о том, как их использовать, а также о том, как iframe может быть полезен для преодоления некоторых сложных ситуаций. Наконец, мы поговорим о том, как вы можете защитить свой iframe, чтобы избежать потенциальных уязвимостей.

Что такое iframe и зачем мы его используем?

Разработчики в основном используют тег iframe для встраивания другого HTML-документа в текущий.

Скорее всего, вы пересекались с ним, когда вам нужно было добавить сторонний виджет (например, знаменитую кнопку «Нравится» на Facebook), видео с YouTube, или рекламный раздел на вашем веб-сайте.

Например, приведенный ниже код будет отображать квадрат размером 500px с главной страницей Google:

<iframe src="https://www.google.com/" height="500px" width="500px"></iframe>

Вот еще один пример, в котором мы показываем кнопку, чтобы твитнуть вашу веб-страницу в Twitter:

<iframe src="https://platform.twitter.com/widgets/tweet_button.html" style="border: 0; width:130px; height:20px;"></iframe>

Когда вы думаете о iframe, вы должны иметь в виду, что он позволяет вам встраивать независимый HTML-документ с его контекстом просмотра.Таким образом, он будет изолирован от JavaScript и CSS родительского элемента. Это одна из веских причин использования iframe — обеспечить определенную степень разделения между вашим приложением и содержимым iframe.

Тем не менее, как вы увидите дальше в этом руководстве, разделение не так что б идеально.Iframe все еще может вести себя раздражающим или злонамеренным образом.
Как пример — вызывать всплывающее окно или автоматически воспроизводить видео.

(*Привет онлайн-казино, и сайтам любителей клубники )

Чтобы проиллюстрировать, насколько удобна эта изоляция от JavaScript и CSS, давайте взглянем на эти две ситуации:

1)В приложении пользователь может создавать электронные письма и сохранять их в качестве шаблонов. На определенной странице мне нужно было перечислить их, чтобы он мог просмотреть и выбрать одно из них. Но чтобы не допустить влияния CSS-кода текущего сайта на стиль этих шаблонов, я поняла, что необходимо использование iframe с атрибутом srcdoc . Это представилось самым чистым решением.

<iframe srcdoc="<html><body>The content you see here will never be affected by the CSS of its parent container. It supposed to be rendered in black on a white background.</body></html>"></iframe> 

*Примечание srcdoc

Позволяет установить содержимое фрейма непосредственно в атрибуте. Значение должно иметь корректный синтаксис HTML, по желанию содержать <!DOCTYPE> и <html> , а также любое количество пробелов, переносов строк, комментариев и других элементов. При одновременном использовании атрибутов src и srcdoc, атрибут src игнорируется .

2)Другая ситуация, когда iframe спасли мне жизнь, возникла, когда пришлось создавать WYSIWYG-редактор для клиента. Проблема была связана с тем, что при помощи этих редакторов вы должны найти способ сохранить возможность производить фокус и выделение, когда пользователь нажимает на любые кнопки в интерфейсе.

Поскольку iframe предлагает изолированную среду, это означает, что фокус или выделение никогда не теряются, когда вы щелкаете за его пределами. Используя события связи между iframe и родителем (подробнее об этом позже в этой статье), мне удалось в одно мгновение создать мощный редактор.

Атрибуты, которые стоило бы знать работая с iframe

На сегодняшний день существует восемь атрибутов, которые мы можем использовать для настройки поведения или стилизации iframe.

<iframe

  src="https://google.com/"    <!-- Устанавливает адрес документа для встраивания --> 

  srcdoc="<p>Some html</p>"    <!-- Устанавливает HTML-содержимое страницы для отображения --> 

  height="100px"               <!-- Устанавливает высоту iframe в пикселях -->

  width="100px"                <!-- Устанавливает ширину iframe в пикселях -->

  name="my-iframe"          <!-- Устанавливает имя iframe (в основном используется для ссылки на элемент в JavaScript -->

  allow="fullscreen"           <!-- Устанавливает политику объектов для iframe.-->

  referrerpolicy="no-referrer" <!-- Настройте реферер для отправки при получении содержимого iframe -->

  sandbox="allow-same-origin"  <!-- Устанавливает ограничения iframe (подробнее об этом ниже) -->
></iframe>

Вы можете найти больше, чем перечисленные выше, но имейте в виду, что они больше не поддерживаются в HTML5: align, frameborder, longdesc, marginheight, marginwidth и scrolling…

*Примечание. По умолчанию элемент iframe имеет рамку вокруг него. Чтобы удалить его, вы можете использовать атрибут style, чтобы установить свойство CSS border в none.

<iframe src="https://logrocket.com/" style="border: none;"></iframe>

iframe события и общение

Загрузка и ошибки

Поскольку iframe является документом, вы можете использовать большинство глобальных обработчиков событий. Когда вы запускаете iframe, есть пара событий, которые могут пригодятся для улучшения работы. Например, отображение счетчика или отдельное сообщение, чтобы помочь пользователю:

load event — cобытие загрузки. Оно запускается, когда iframe полностью загружен. Другими словами, все статические ресурсы были загружены, и все элементы в дереве DOM вызвали событие load.

Событие ошибки — error event которое вызывается при сбое загрузки.

Вы можете прослушивать их с помощью атрибутов onload и onerror соответственно:

<iframe src="https://logrocket.com/" onload="onLoad()" onerror="onError()"></iframe>

Если хотите, то вы можете добавить слушателей в свой iframe программно.

// Для нового iframe
const iframe = document.createElement("iframe");

iframe.onload = function() {
  console.log("iframe загрузился");
};
iframe.onerror = function() {
  console.log("Что-то пошло не так, давай, ищи ошибку!");
};

iframe.src = "https://logrocket.com/";
document.body.appendChild(iframe);

// Для существующего iframe
const iframe = document.querySelector('.my-iframe');

iframe.onload = function() {
  console.log("iframe загрузился");
}
iframe.onerror = function() {
  console.log("Что-то пошло не так, давай, ищи ошибку!");
}

Общение с фреймами

Довольно легко отправлять сообщения между родителем и iframe. Вы должны использовать функцию postMessage, которая описана в MDN здесь.

От родителя к фрейму

Отправьте сообщение от родительского элемента:

const myiframe = document.getElementById('myIframe');

myIframe.contentWindow.postMessage('message', '*');

И послушайте его в iframe:

window.onmessage = function(event){
    if (event.data == 'message') {
        console('Message received!');
    }
};

От iframe к родителю

Отправьте сообщение из iframe:

window.top.postMessage('reply', '*')

И прослушай это у родителя:

window.onmessage = function(event){
    if (event.data == 'reply') {
        console('Reply received!');
    }
};

Примечание: имейте в виду, что вы можете оказаться в некоторых хитрых ситуациях, когда вам нужно что-то отладить, так как сообщения запускаются и забываются (fire-and-forget) (иначе говоря. — нет реальной обработки ошибок).

Безопасность

Когда вы используете iframe, вы в основном имеете дело с контентом, полученным от третьей стороны, который вы не можете контролировать.

Таким образом, вы повышаете риск потенциальной уязвимости в вашем приложении или просто сталкиваетесь с плохим пользовательским интерфейсом (например, раздражающим автоматическим воспроизведением видео).

К счастью, вы можете занести в черный список или белый список конкретные функции.

Вы должны использовать sandbox (песочницу) и allow(допустимые) атрибуты.

! Помните, хорошее эмпирическое правило — всегда предоставлять минимальный уровень возможностей, необходимый ресурсу для его работы. Эксперты по безопасности называют эту концепцию «принципом наименьших привилегий».

Атрибут sandbox

Вот полный список флагов песочницы и их назначение:

Вы несете ответственность, какие привилегии вы можете предоставить каждому iframe.

Например, если вашему iframe нужно только отправить формы и открыть новые модальные окна, вот как вы настроите атрибут песочницы:

<iframe sandbox="allow-forms allow-modals" src="https://www.something.com/"></iframe>

В случае, когда атрибут песочницы настроен, а одна функция не работает правильно в ресурсе, это может быть связано с отсутствием определенного флага.
Убедитесь, что вы знаете о них больше, чтобы отладить вещи быстро.
Кроме того, имейте в виду, что использование пустого атрибута «песочница» полностью создаст «песочницу» для iframe.

Это означает, что JavaScript внутри iframe не будет выполняться, а все перечисленные выше привилегии будут ограничены (*например, создание новых окон или загрузка плагина).

Пустой атрибут песочницы в основном используется для статического содержимого, но это значительно снизит возможности, необходимые для правильной работы других ресурсов.

<iframe sandbox="allow-forms allow-modals" src="https://www.something.com/"></iframe>

Примечание. Атрибут песочницы не поддерживается в Internet Explorer 9 и более ранних версиях.

Атрибут allow

Этот атрибут allow в настоящее время является экспериментальным и поддерживается только браузерами на основе Chromium. Это позволяет вам разрешить определенные функции белого списка, такие как доступ iframe к акселерометру, информации об аккумуляторе или камере.

Доступно более 25 флагов, поэтому я не буду перечислять их все здесь. Вы можете просмотреть их в документации по политике в отношении функциональных возможностей Mozilla.

Я суммировала самые популярные в таблице ниже:

Что нужно знать о фреймах

Как решать проблемы с браузерами, которые не поддерживают фреймы

Если браузер не поддерживает iframe, он будет отображать содержимое, включенное между открывающим тегом <iframe> и закрывающим тегом </ iframe>.

Таким образом, вы всегда должны думать о том, чтобы разместить предупреждающее сообщение как запасной вариант для этих пользователей.

<iframe>
  <p>Твой браузер устарел для отображения элемента iframe</p>
</iframe>

Как вы можете сделать так, чтобы iframe был частью родительского документа (т.е. без границ и полос прокрутки)?

Для этой цели был введен бесшовный атрибут seamless. Он все еще экспериментален и плохо поддерживается в браузерах (это понимают только Chromium).

*Примечание Он также не является частью спецификации W3C HTML5 на момент написания этой статьи. Ознакомиться тут

<iframe seamless src="https://logrocket.com/"></iframe>

Могут ли iframes повлиять на SEO моего сайта?

Я мало что знала об этом, поэтому мне пришлось немного покопаться. Есть много спекуляций вокруг этой темы.

Долгое время краулеры не могли понять содержимое iframes, но это уже не так. Наиболее релевантный ответ, который я нашла, был из этой статьи, и сегодняшний вывод выглядит так:

“Поскольку поисковые системы считают, что содержимое в фреймах принадлежит другому веб-сайту, лучшее, на что вы можете надеяться, — это отсутствие эффекта. Iframes, как правило, не помогают и не повреждают ваш рейтинг в поисковых системах. “

Таким образом, лучше всего предположить, что контент, отображаемый с помощью iframes, может быть не проиндексирован или недоступен для отображения в результатах поиска Google. Обходным путем может быть предоставление дополнительных текстовых ссылок на контент, который они отображают, чтобы робот Googlebot мог сканировать и индексировать этот контент.

Примечание. Вам также не следует беспокоиться о проблемах с дублированием контента, поскольку сканеры сегодня обычно их распознают.

Могут ли фреймы повлиять на скорость загрузки моего сайта?

Каждый iframe на странице увеличивает объем используемой памяти, а также другие вычислительные ресурсы, такие как пропускная способность.Поэтому не следует чрезмерно использовать iframe, не следя за тем, что происходит, иначе вы можете повредить производительности своей страницы.

Чтобы избежать того, что ваши фреймы замедляют работу ваших страниц, хорошим способом является их ленивая загрузка (т.е. загрузка их только тогда, когда они необходимы, например, когда пользователь прокручивает рядом с ними).Этого легко добиться, просто добавив в тег атрибут loading = «lazy».

Имейте в виду, что все современные браузеры на основе Chromium поддерживают это на момент написания этой статьи. Вас заинтересует библиотека lazyload, которая работает везде.

<iframe src = "https://logrocket.com/" loading = "lazy"> </ iframe>

Примечание. Атрибут loading = «lazy» также работает с тегом img, если вы еще этого не знали.

Как я могу сделать iframe отзывчивым?

По мере того, как все больше людей просматривают Интернет с помощью своих телефонов, важно убедиться, что каждый из ваших интерфейсов отзывчивый.Но как это сделать, если на вашей странице есть фрейм?

Мы могли бы посвятить целое руководство относительно множества способов сделать ваш iframe отзывчивым. Вместо этого я просто сошлюсь на две отличные статьи:

  • Эта первая статья (возможно, с самым простым решением) покажет вам, как этого добиться, обернув свой iframe в другой элемент HTML и добавив в него несколько свойств CSS.
  • Эта вторая статья покажет вам, как сделать iframe отзывчивым, имея дело с соотношениями сторон.
  • Существует также библиотека Iframe Resizer, но имейте в виду, что она поставляется с множеством дополнительных функций, которые вам могут и не понадобиться, и просто раздуют ваш код.

Примечание. Если вы используете библиотеку начальной загрузки в своем проекте, есть embed-responsive и встроенные embed-responsive-16by9, которые вы можете использовать прямо из коробки, чтобы адаптировать свои фреймы.

<div class="embed-responsive embed-responsive-16by9">
  <iframe src="https://logrocket.com/" loading="lazy"></iframe>
</div>

Как предотвратить появление белой вспышки во время загрузки iframe

Да, друзья мои, для этого есть решение. В этой статье Крис Койер делится небольшим фрагментом, который скрывает все iframes на странице с помощью некоторого CSS-кода и удаляет его до тех пор, пока окно не будет загружено, а затем сделает их видимыми.

Как перезагрузить содержимое iframe

Легче лёгкого! Поскольку вы можете получить доступ к элементу окна iframe с помощью contentWindow, вы должны сделать это:

// Get the iframe
const iframe = document.getElementById('myIframe');  
// Reload the iframe
iframe.contentWindow.location.reload();

Я надеюсь, что это руководство помогло вам улучшить ваши знания о фреймах.
Хотя они могут быть небезопасными, если вы загружаете ненадежный контент, они также предлагают некоторые существенные преимущества. Поэтому вам не следует полностью исключать их из своего развивающегося арсенала, а использовать их только в соответствующих ситуациях.

Если у вас есть что добавить в эту статью, вы можете связаться со мной в комментариях ниже или просто пинговать меня в Twitter @RifkiNada

Сделаем web лучше.

Содержание

  1. Resource loading: onload and onerror
  2. Loading a script
  3. script.onload
  4. script.onerror
  5. Other resources
  6. Crossorigin policy
  7. Загрузка ресурсов: onload и onerror
  8. Загрузка скриптов
  9. script.onload
  10. script.onerror
  11. Другие ресурсы
  12. Ошибка в скрипте с другого источника
  13. Поймать ошибку, если iframe src не загружается. Ошибка: — » отказано в отображении «http://www.google.co.in-в рамке..»
  14. 6 ответов
  15. вторая проблема
  16. Ошибка перехвата, если iframe src не загружается. Ошибка: — «Не удалось отобразить» http://www.google.co.in/ «во фрейме ..»
  17. Вторая проблема
  18. Как отловить ошибки JavaScript во всех фреймах (с помощью window.error)?
  19. 2 ответы

Resource loading: onload and onerror

The browser allows us to track the loading of external resources – scripts, iframes, pictures and so on.

There are two events for it:

  • onload – successful load,
  • onerror – an error occurred.

Loading a script

Let’s say we need to load a third-party script and call a function that resides there.

We can load it dynamically, like this:

…But how to run the function that is declared inside that script? We need to wait until the script loads, and only then we can call it.

For our own scripts we could use JavaScript modules here, but they are not widely adopted by third-party libraries.

script.onload

The main helper is the load event. It triggers after the script was loaded and executed.

So in onload we can use script variables, run functions etc.

…And what if the loading failed? For instance, there’s no such script (error 404) or the server is down (unavailable).

script.onerror

Errors that occur during the loading of the script can be tracked in an error event.

For instance, let’s request a script that doesn’t exist:

Please note that we can’t get HTTP error details here. We don’t know if it was an error 404 or 500 or something else. Just that the loading failed.

Events onload / onerror track only the loading itself.

Errors that may occur during script processing and execution are out of scope for these events. That is: if a script loaded successfully, then onload triggers, even if it has programming errors in it. To track script errors, one can use window.onerror global handler.

Other resources

The load and error events also work for other resources, basically for any resource that has an external src .

There are some notes though:

  • Most resources start loading when they are added to the document. But is an exception. It starts loading when it gets a src (*) .
  • For , the iframe.onload event triggers when the iframe loading finished, both for successful load and in case of an error.

That’s for historical reasons.

Crossorigin policy

There’s a rule: scripts from one site can’t access contents of the other site. So, e.g. a script at https://facebook.com can’t read the user’s mailbox at https://gmail.com .

Or, to be more precise, one origin (domain/port/protocol triplet) can’t access the content from another one. So even if we have a subdomain, or just another port, these are different origins with no access to each other.

This rule also affects resources from other domains.

If we’re using a script from another domain, and there’s an error in it, we can’t get error details.

For example, let’s take a script error.js that consists of a single (bad) function call:

Now load it from the same site where it’s located:

Источник

Загрузка ресурсов: onload и onerror

Браузер позволяет отслеживать загрузку сторонних ресурсов: скриптов, ифреймов, изображений и др.

Для этого существуют два события:

  • load – успешная загрузка,
  • error – во время загрузки произошла ошибка.

Загрузка скриптов

Допустим, нам нужно загрузить сторонний скрипт и вызвать функцию, которая объявлена в этом скрипте.

Мы можем загрузить этот скрипт динамически:

…Но как нам вызвать функцию, которая объявлена внутри того скрипта? Нам нужно подождать, пока скрипт загрузится, и только потом мы можем её вызвать.

Для наших собственных скриптов мы можем использовать JavaScript-модули, но они не слишком широко распространены в сторонних библиотеках.

script.onload

Главный помощник – это событие load . Оно срабатывает после того, как скрипт был загружен и выполнен.

Таким образом, в обработчике onload мы можем использовать переменные, вызывать функции и т.д., которые предоставляет нам сторонний скрипт.

…А что если во время загрузки произошла ошибка? Например, такого скрипта нет (ошибка 404), или сервер был недоступен.

script.onerror

Ошибки, которые возникают во время загрузки скрипта, могут быть отслежены с помощью события error .

Например, давайте запросим скрипт, которого не существует:

Обратите внимание, что мы не можем получить описание HTTP-ошибки. Мы не знаем, была ли это ошибка 404 или 500, или какая-то другая. Знаем только, что во время загрузки произошла ошибка.

Обработчики onload / onerror отслеживают только сам процесс загрузки.

Ошибки обработки и выполнения загруженного скрипта ими не отслеживаются. Чтобы «поймать» ошибки в скрипте, нужно воспользоваться глобальным обработчиком window.onerror .

Другие ресурсы

События load и error также срабатывают и для других ресурсов, а вообще, для любых ресурсов, у которых есть внешний src .

Однако есть некоторые особенности:

  • Большинство ресурсов начинают загружаться после их добавления в документ. За исключением тега . Изображения начинают загружаться, когда получают src (*) .
  • Для событие load срабатывает по окончании загрузки как в случае успеха, так и в случае ошибки.

Такое поведение сложилось по историческим причинам.

Ошибка в скрипте с другого источника

Есть правило: скрипты с одного сайта не могут получить доступ к содержимому другого сайта. Например, скрипт с https://facebook.com не может прочитать почту пользователя на https://gmail.com .

Или, если быть более точным, один источник (домен/порт/протокол) не может получить доступ к содержимому с другого источника. Даже поддомен или просто другой порт будут считаться разными источниками, не имеющими доступа друг к другу.

Это правило также касается ресурсов с других доменов.

Если мы используем скрипт с другого домена, и в нем имеется ошибка, мы не сможем узнать детали этой ошибки.

Для примера давайте возьмём мини-скрипт error.js , который состоит из одного-единственного вызова функции, которой не существует:

Теперь загрузим этот скрипт с того же сайта, на котором он лежит:

Источник

Поймать ошибку, если iframe src не загружается. Ошибка: — » отказано в отображении «http://www.google.co.in-в рамке..»

я использую Knockout.js для привязки тег iframe src tag (это будет настраиваться по отношению к пользователю).

теперь, если пользователь настроил http://www.google.com (я знаю, что он не будет загружаться в iframe, поэтому я использую его для сценария-ve), и это должно быть показано в IFrame. но он бросает ошибку:-

отказался показывать’http://www.google.co.in/ ‘ в рамке, потому что это установите ‘X-Frame-Options’ в ‘SAMEORIGIN’.

у меня есть следующий код для iframe:-

то, что я хочу, если url-адрес не загружается. Я хочу показать Таможни. СКРИПКА ЗДЕСЬ

теперь, если я использую onload и onerror как: —

он работает отлично загрузка w3schools.com но не с google.com.

Secondly: — если я сделаю это как функцию и попробую, как я сделал в моей скрипке, это не работает.

Я не знаю, как я должен заставить его работать и захватить ошибку.

отредактировано: — я видел хотите вызвать функцию, если iframe не загружается или load’s вопрос в stackoverflow, но он показывает ошибку для сайтов, которые могут быть загружены в iframe.

6 ответов

вы не сможете сделать этого со стороны клиента из-за Та Же Политика Происхождения установленных браузерах. Вы не сможете получить много информации из кадра, помимо основных свойств, таких как ширина и высота.

кроме того, google устанавливает в своем заголовке ответа»X-Frame-Options ‘ of SAMEORIGIN.

даже если вы сделали вызов ajax в google, вы не сможете проверить ответ, потому что браузер применяет тот же источник Политика.

Итак, единственный вариант-сделать запрос с вашего сервера, чтобы увидеть, можете ли вы отобразить сайт в своем IFrame.

Так, на вашем сервере.. ваше веб-приложение сделает запрос на www.google.com а затем проверьте ответ, чтобы увидеть, имеет ли он аргумент заголовка X-Frame-Options. Если он существует, то вы знаете, что IFrame будет ошибкой.

Я думаю, что вы можете связать load событие iframe, событие срабатывает при полной загрузке содержимого iframe.

в то же время вы можете запустить setTimeout, если iframe загружен очистить тайм-аут альтернативно пусть тайм-аут огонь.

вторая проблема

это потому, что вы пропустите parens в inline вызов функции; попробуйте изменить это:

onload всегда будет триггером, я slove эта проблема использует блок try catch.Он выдаст исключение при попытке получить contentDocument.

я столкнулся с аналогичной проблемой. Я решил это без использования обработчика onload.Я работал над проектом AngularJs, поэтому использовал $interval и $ timeout. U также можно использовать setTimeout и setInterval.Вот код:

каждые 0,4 секунды продолжайте проверять голову документа iFrame. Я что-то присутствую.Загрузка не была остановлена CORS, так как ошибка CORS показывает пустую страницу. Если после 5 секунд ничего нет, произошла ошибка (политика Cors) и т. д.. Шоу подходит сообщение.Спасибо. Надеюсь, это решит твою проблему.

Это небольшая модификация ответа Edens — который для меня в chrome не поймал ошибку. Хотя вы все равно получите ошибку в консоли: «Отказался показывать»https://www.google.ca/ ‘в кадре, потому что он установил» X-Frame-Options » в «sameorigin».»По крайней мере, это поймает сообщение об ошибке, и тогда вы сможете справиться с ним.

У меня такая же проблема, chrome не может запустить onerror при ошибке загрузки iframe src.

но в моем случае, Мне просто нужно сделать междоменный http-запрос, поэтому я использую скрипт src/onload / onerror вместо iframe. он хорошо работает.

Источник

Ошибка перехвата, если iframe src не загружается. Ошибка: — «Не удалось отобразить» http://www.google.co.in/ «во фрейме ..»

Я использую Knockout.js для привязки src тега iframe (это можно настроить в соответствии с пользователем).

Теперь, если пользователь настроил http://www.google.com (я знаю, что он не будет загружаться в iframe, поэтому я использую его для сценария -ve), и это должно быть показано в IFrame. но это вызывает ошибку: —

Отказался отображать » http://www.google.co.in/ » во фрейме, потому что для параметра «X-Frame-Options» установлено значение «SAMEORIGIN».

У меня есть следующий код для Iframe: —

Я хочу, чтобы URL-адрес не загружался. Я хочу отображать настраиваемое сообщение . FIDDLE ЗДЕСЬ

Теперь, если я использую onload и onerror как: —

Он отлично работает при загрузке w3schools.com, но не с google.com.

Во-вторых: — если я сделаю это как функцию и попробую, как я сделал на своей скрипке, это не сработает.

Я не знаю, как мне запустить его и зафиксировать ошибку.

Отредактировано: — Я видел, что хочу вызвать функцию, если iframe не загружает или не загружает вопрос в stackoverflow, но показывает ошибку для сайтов, которые могут быть загружены в iframe.

Вы не сможете сделать это на стороне клиента из-за той же политики происхождения, установленной браузерами. Вы не сможете получить из iFrame много информации, кроме основных свойств, таких как ширина и высота.

Кроме того, Google устанавливает в своем заголовке ответа « X-Frame-Options » SAMEORIGIN.

Даже если вы выполнили ajax-вызов в Google, вы не сможете проверить ответ, потому что браузер применяет ту же политику происхождения.

Итак, единственный вариант — сделать запрос с вашего сервера, чтобы узнать, можете ли вы отобразить сайт в своем IFrame.

Итак, на вашем сервере . ваше веб-приложение отправит запрос на www.google.com, а затем проверит ответ, чтобы увидеть, есть ли у него аргумент заголовка X-Frame-Options. Если он существует, вы знаете, что IFrame выдаст ошибку.

Я думаю, что вы можете привязать load событие iframe, событие срабатывает, когда содержимое iframe полностью загружено.

В то же время вы можете запустить setTimeout, если iFrame загружен, сбросьте тайм-аут или позвольте тайм-ауту сработать.

Вторая проблема

Это потому, что вы пропустили скобки в вызове встроенной функции; попробуйте изменить это:

Источник

Как отловить ошибки JavaScript во всех фреймах (с помощью window.error)?

Я знаю, что можно добавить прослушиватель событий для window.error.

Однако при работе с iframe каждый iframe имеет свой собственный оконный элемент, и window.error должны быть созданы для каждого и каждого iframe .

Можно ли каким-то образом определить обработчик событий ошибки в одном месте, где все ошибки будут запускать этот конкретный метод?

2 ответы

Это может сработать.

ответ дан 30 авг.

Спасибо за это. выглядит красиво, хотя кажется не идеальным для моего приложения — IFrames и окна создаются на лету, и я не могу контролировать большую часть из них, поэтому я не могу заранее знать все выигрышные объекты. Я предполагаю, что в окне IE нет глобального способа обработки ошибок? Спасибо, Таль. — Долина

ах, в таком случае . в каждый создаваемый вами фрейм просто добавляйте . window.onerror = top.myHandler; — Scunliffe

да . но я заранее не знаю, что будет источником iframe. (используя отправку формы в целевой IFrame) — ошибка window.onerror должна быть внутри самого кода IFrame .. — Долина

Хм, у вас есть глобальный JS-файл, который вы включаете во все фреймы? если да, то может ли туда попасть ваш обработчик ошибок? и подключаться к каждому окну при загрузке файла сценария? В зависимости от того, какая информация вам нужна / нужна в обработчике ошибок, вы можете проверить родительский [n] и дочерний [n] фреймы, чтобы определить иерархию в обработчике ошибок. Из интереса . что ты делаешь с обработчиком? например, выполняете ли вы обратный вызов AJAX для регистрации ошибок / поддержки системы электронной почты? или вы просто предупреждаете пользователя «красивым» способом? — Scunliffe

Есть несколько фреймов с глобальным JS, и это хорошая идея. Некоторые iframe не имеют ничего общего и создаются динамически — какие мысли по этому поводу? Что касается обработчика ошибок — я думаю о том, чтобы сделать обратный вызов AJAX для поддержки. но в настоящее время это сохраняется только на стороне клиента в некоторой строке для последующего просмотра. — Долина

Я не пробовал этого, поэтому, пожалуйста, не вешайте меня за это 🙂 В главном / родительском окне, которое содержит все фреймы, вы можете создать там свою функцию обработки ошибок. Затем используйте jQuery, чтобы захватить все ваши iFrames на вашей странице и зарегистрируйте обработчик .error, чтобы указать на вашу функцию, зарегистрированную в родительском окне.

Источник

The browser helps to track the loading of external resources, such as pictures, scripts and more.

Two primary events are used for that purpose:

  • onload: it supposes a successful load.
  • onerror: it means that an error has occurred.

Imagine that you should load a third-party script and call a function residing there, as illustrated below:

let script = document.createElement('script');
script.src = "script.js";
document.head.append(script);

To run the function declared inside that script, you should wait until the script loads and only then call it.

Please note, that here you could also use JavaScript modules, but they are not widely used by third-party libraries.

Script.onload

The load event is the main helper here. It occurs once the was already loaded and executed.

Here is an example of the load event:

w3docs logo
javascript loading script file

let script = document.createElement(‘script’);
// any script can be loading from any domain
script.src = «https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.3.0/lodash.js»
document.head.append(script);
script.onload = function () {
// the script generates an auxiliary function
alert(_); // the function available
};

So, Script variables and run functions can be used in download.

But, the loading may fail. Note that there isn’t any such script (error 404) or the server is done.

Let’s see what happens in such a circumstance.

Script.onerror

Errors occurring during the script loading are tracked in an error event.

Let’s take a look at an example of requesting a non-existing script:

w3docs logo
javascript loading script onerror

let script = document.createElement(‘script’);
script.src = «https://example.com/404.js»; // no such script
document.head.append(script);
script.onerror = function () {
alert(«Loading an error » + this.src); // Loading an error https://example.com/404.js
};

Please, take into account that the details of the HTTP error are not available here: you can’t know whether it’s an error 404, 500 or anything else.

Another important thing to note: the onload and onerror events track only the loading itself. In other words, errors occurring during the script processing and execution are out of the framework. So, if a script loaded efficiently, then onload happens, even if it includes some programming errors. For tracking the script errors, you can use a global handler called window.onerror.

The load and error events operate for any other resources that have an external src, like in the example below:

w3docs logo
javascript load and error events

let img = document.createElement(‘img’);
img.src = «https://www.w3docs.com/uploads/media/default/0001/05/9eb9e9cba721ba3bb5e653751449173197f2924a.png»; // (*)
img.onload = function () {
alert(`Image loaded, size ${img.width}x${img.height}`);
};
img.onerror = function () {
alert(«An error occurred while loading image»);
};

But, note that several resources begin loading once they are added to the document. The <img> is an exception to the rule. It begins to load after getting a src (*).

For <iframe>, the iframe.onload event occurs once the iframe loading is over. It is both for the efficient load and in case of an error.

Scripts from one site don’t have access to the scripts of the other one. For example, a script at https://www.instagram.com/ can’t read the user’s mailbox at https://gmail.com.

In other words, one origin (domain/port/protocol) can’t access the content of the other one. Even in case of having a subdomain, these are considered different origins.

The rule above affects the resources from other domains, as well.
An example of a script error.js consisting of a single (bad) function call is demonstrated below:

//  error.js
noSuchFunction();

If you try loading it from the same site where it’s located, you will have this:

<script>
  window.onerror = function(message, url, line, col, errorObj) {
    alert(`${message}n${url}, ${line}:${col}`);
  };
</script>
<script src="/article/onload-onerror/crossorigin/error.js"></script>

A good error report can be seen here:

Uncaught ReferenceError: noSuchFunction is not defined
https://javascript.info/article/onload-onerror/crossorigin/error.js, 1:1

The example of loading the same script from another domain will look like this:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
  </head>
  <body>
    <script>
      window.onerror = function(message, url, line, col, errorObj) {
        alert(`${message}n${url}, ${line}:${col}`);
      };
    </script>
    <script src="https://cors.javascript.info/article/onload-onerror/crossorigin/error.js"></script>
  </body>
</html>

So, there is a different report here:

Script error.
, 0:0

There can be different details, depending on the browser. However, idea remains the same: any information regarding the internals of a script is hidden. The reason is that it is from a different domain.

Still, it is important to know details about errors.

There are services, listening for global errors using window.onerror, saving errors and providing an interface to access and analyze them. So, they make it possible to see real errors, triggered by the users. But, if a script has another origin, no more information will be available.

For allowing cross-origin access, the <script> tag should have the crossorigin attribute. The remote server has to provide specific headers.

Three levels of cross-origin access exist:

  1. No crossorigin attribute — the access is not allowed.
  2. For crossorigin="anonymous" the access is allowed, in case the server responds with the header Access-Control-Allow-Origin including or the origin. Any authorization information or cookies are sent to the remote server.
  3. crossorigin="use-credentials": the access is allowed in case the server sends back the Access-Control-Allow-Origin header with the origin and Access-Control-Allow-Credentials: true. Authorization information and cookies are sent to the remote server.

In case of not having any crossorigin attribute, the access will be prohibited.

So, let’s see how to add it.

You can choose between "anonymous" and "use-credentials".
In the event of not caring about the cookies, "anonymous" is the way to go, like this:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
  </head>
  <body>
    <script>
      window.onerror = function(message, url, line, col, errorObj) {
        alert(`${message}n${url}, ${line}:${col}`);
      };
    </script>
    <script crossorigin="anonymous" src="https://cors.javascript.info/article/onload-onerror/crossorigin/error.js"></script>
  </body>
</html>

Supposing that the server provides Access-Control-Allow-Origin header, the full error report is ready.

Resources such as scripts, styles, images provide load and error events for tracking their loading:

  • The load event happens on a successful load.
  • The error event occurs on a failed load.

, there is an exception: <iframe>, which only triggers the load, for each load completion, even if the page is not found. For resources, you can also use the readystatechange event. But it is used rarely as the load and error events are simpler and handier.

Written by Nada Rifki✏️

The iframe element (short for inline frame) is probably among the oldest HTML tags and was introduced in 1997 with HTML 4.01 by Microsoft Internet Explorer.

Even though all modern browsers support them, many developers write endless articles advising against using them.

I believe that their bad reputation should not prevent you from relying on them. They have many legitimate uses cases.

Besides, it’s not that hard to secure them, so you won’t have to worry about your user’s computer becoming infected.

To help you form your own opinion and sharpen your developer skills, we will cover all the essentials you should know about this controversial tag.

We’ll go through most of the features the iframe element provides and talk about how you use them, as well as how iframe can be useful for overcoming some tricky situations. Finally, we’ll talk about how you can secure your iframe to avoid potential vulnerabilities.

LogRocket Free Trial Banner

What is an iframe, and when do you use it?

Developers mainly use the iframe tag to embed another HTML document within the current one.

You may have crossed paths with it when you had to include a third-party widget (like the famous Facebook like button), a YouTube video, or an advertising section on your website.

For instance, the code below will display a 500px square with the google homepage within:

<iframe src="https://www.google.com/" height="500px" width="500px"></iframe>

Enter fullscreen mode

Exit fullscreen mode

Here is another example in which we display a button to tweet your web page on Twitter:

<iframe src="https://platform.twitter.com/widgets/tweet_button.html" style="border: 0; width:130px; height:20px;"></iframe>

Enter fullscreen mode

Exit fullscreen mode

What you must keep in mind when thinking about an iframe is that it lets you embed an independent HTML document with its browsing context.

Thus, it will be isolated from the JavaScript and CSS of the parent. That is one of the valid purposes to use an iframe: to provide a measure of separation between your application and the iframe content.

Nonetheless, as you will see in this guide, the separation is not so perfect.

The iframe can still behave in annoying or malicious ways: triggering a popup or auto-playing videos for instance.

To illustrate how this isolation from the JavaScript and CSS is handy, let’s take a look at these two situations:

In an application, the user could create emails and save them as templates. On a particular page, I needed to list them to let him preview and choose one.

But, to prevent the CSS of the current website from affecting the style of these templates, I figured out that using an iframe with the srcdoc attribute was the cleanest solution.

<iframe srcdoc="<html><body>The content you see here will never be affected by the CSS of its parent container. It supposed to be rendered in black on a white background.</body></html>"></iframe>

Enter fullscreen mode

Exit fullscreen mode

The other situation when iframes saved my life was when I had to build a WYSIWYG editor for a customer. But the thing with these editors is that you have to find a way to keep the focus and the selection when the user is clicking on all the buttons across the interface.

Because an iframe offers an isolated environment, this means that the focus or the selection is never lost when you are clicking outside of it.

By using communication events between the iframe and the parent (more on how to do so later in this article), I managed to design a powerful editor in a snap.

The attributes you need to know

To this day, there are eight attributes we can use to customize the behavior or styling of an iframe.

<iframe

  src="https://google.com/"    <!-- Sets the address of the document to embed --> 

  srcdoc="<p>Some html</p>"    <!-- Sets the HTML content of the page to show --> 

  height="100px"               <!-- Sets the iframe height in pixels -->

  width="100px"                <!-- Sets the iframe width in pixels -->

  name="my-iframe"             <!-- Sets the name of the iframe (mainly used to reference the element in JavaScript -->

  allow="fullscreen"           <!-- Sets the feature policy for the iframe. -->

  referrerpolicy="no-referrer" <!-- Set the referrer to send when fetching the iframe content -->

  sandbox="allow-same-origin"  <!-- Sets the restrictions of the iframe (more on this below) -->

></iframe>

Enter fullscreen mode

Exit fullscreen mode

You may find more than the ones listed above, but keep in mind that they are not supported in HTML5 anymore: align, frameborder, longdesc, marginheight, marginwidth and scrolling.

Note : By default, the iframe element has a border around it. To remove it, you can use the style attribute to set the border CSS property to none.

<iframe src="https://logrocket.com/" style="border: none;"></iframe>

Enter fullscreen mode

Exit fullscreen mode

iframe events and communication

Loading and errors

Because an iframe is a document, you can use most global event handlers.

When you are initiating the iframe, two of them come in handy to improve the experience, like displaying a spinner or a specific message to assist the user:

  • The load event. It is triggered when the iframe is fully loaded. In other words, all static assets have been downloaded, and all the elements in the DOM tree have fired their load event.

  • The error event that is triggered when the loading failed.

You can listen to them with the onload and onerror attribute respectively:

<iframe src="https://logrocket.com/" onload="onLoad()" onerror="onError()"></iframe>

Enter fullscreen mode

Exit fullscreen mode

Or if you can add the listeners to your iframe programmatically.

// For a new iframe
const iframe = document.createElement("iframe");

iframe.onload = function() {
  console.log("The iframe is loaded");
};
iframe.onerror = function() {
  console.log("Something wrong happened");
};

iframe.src = "https://logrocket.com/";
document.body.appendChild(iframe);

// For an existing iframe
const iframe = document.querySelector('.my-iframe');

iframe.onload = function() {
  console.log("The iframe is loaded");
}
iframe.onerror = function() {
  console.log("Something wrong happened");
}

Enter fullscreen mode

Exit fullscreen mode

Communication with iframes

It is quite easy to send messages between the parent and the iframe. You have to use the postMessage function, which is documented here).

From the parent to the iframe

Send the message from the parent element:

const myiframe = document.getElementById('myIframe')

myIframe.contentWindow.postMessage('message', '*');

Enter fullscreen mode

Exit fullscreen mode

And listen to it in the iframe:

window.onmessage = function(event){
    if (event.data == 'message') {
        console('Message received!');
    }
};

Enter fullscreen mode

Exit fullscreen mode

From the iframe to the parent

Send the message from the iframe:

window.top.postMessage('reply', '*')

Enter fullscreen mode

Exit fullscreen mode

And listen to it in the parent:

window.onmessage = function(event){
    if (event.data == 'reply') {
        console('Reply received!');
    }
};

Enter fullscreen mode

Exit fullscreen mode

Note : Keep in mind that you can end up in some tricky situations when you need to debug something as messages are fire-and-forget (i.e., there is no real error handling).

Security

When you are using an iframe, you are mostly dealing with content coming from a third party over which you have no control.

Thus, you are increasing the risk of having a potential vulnerability in your application or simply having to deal with a bad user experience (like annoying video auto-play ).

Thankfully, you can blacklist or whitelist specific features.

You have to use the sandbox and allow the attributes we discussed earlier.

Keep in mind that a good rule of thumb is to always grant the minimum level of capability necessary to a resource to do its job. Security experts refer to this concept as “the principle of least privilege.”

The sandbox attribute

Here is the complete list of sandboxing flags and their purposes:

Flag Details
allow-forms Allows form submission.
allow-modals Allows the resource to open new modal windows.
allow-orientation-lock Allows the resource to lock the screen orientation.
allow-pointer-lock Allows the resource to use the Pointer Lock API.
allow-popups Allows the resource to open new popups or tabs.
allow-popups-to-escape-sandbox Allows the resource to open new windows that will not inherit the sandboxing.
allow-presentation Allows the resource to start a presentation session.
allow-same-origin Allows the resource to maintain its origin.
allow-scripts Allows the resource to run scripts.
allow-top-navigation Allows the resource to navigate the top-level browsing context.
allow-top-navigation-by-user-activation Allows the resource to navigate the top-level browsing context, but only if initiated by a user gesture.

It is up to you to define which privileges you can grant to each iframe.

For instance, if your iframe only needs to submit forms and to open new modal windows, here is how you will configure the sandbox attribute:

<iframe sandbox="allow-forms allow-modals" src="https://www.something.com/"></iframe>

Enter fullscreen mode

Exit fullscreen mode

For a situation when the sandbox attribute is configured, and one feature is not working correctly within the resource, it might be because it lacks a specific flag.

Make sure you know more about them to debug things quickly.

Also, keep in mind that using an empty sandbox attribute will fully sandbox the iframe.

This means that the JavaScript inside the iframe will not be executed, and all the privileges listed above will be restricted (like creating new windows or loading a plugin).

The empty sandbox attribute is mostly using for static content but will drastically reduce the capability required for other resources to work properly.

<iframe sandbox="allow-forms allow-modals" src="https://www.something.com/"></iframe>

Enter fullscreen mode

Exit fullscreen mode

Note : The sandbox attribute is unsupported in Internet Explorer 9 and earlier.

The allow attribute

This allow attribute is currently experimental and only supported by Chromium-based browsers. It lets you allow whitelist specific features like letting the iframe access to the accelerometer, the battery information, or the camera.

There are more than 25 available flags, so I will not list them all here. You can browse them on the Mozilla Feature Policy Documentation. I summarized the most popular in the table below:

Flag Details
accelerometer Allows access the Accelerometer interface
ambient-light-sensor Allows access the AmbientLightSensor interface
autoplay Allows to autoplay video and audio files
battery Allows access to the Battery Status API
camera Allows access to the camera
fullscreen Allows access to fullscreen mode
geolocation Allows access to the Geolocation API
gyroscope Allows access to the Sensors API Gyroscope interface
magnetometer Allows access to the Sensors API Magnetometer interface
microphone Allows access to the device microphone
midi Allows access to the Web MIDI API
payment Allows access to the Payment Request API
usb Allows access to the WebUSB API
vibrate Allows access to the Vibration API

Things to know about iframes

How to deal with browsers that do not support iframes

If a browser does not support an iframe, it will display the content included between the opening <iframe> tag and the closing </iframe> tag.

Thus, you should always think about placing a warning message as a fallback for those poor users.

<iframe>
  <p>Your browser does not support iframes.</p>
</iframe>

Enter fullscreen mode

Exit fullscreen mode

How can you render the iframe like it is actually part of the parent document (i.e., no borders and scrollbars) ?

🤓The seamless attribute has been introduced for this exact purpose. It is still experimental and poorly supported among browsers (only Chromium-based understand it).

It’s also not part of the W3C HTML5 specification at the time of this writing.

<iframe seamless src="https://logrocket.com/"></iframe>

Enter fullscreen mode

Exit fullscreen mode

Can iframes effect the SEO of my website?

I did not know much about this, so I had to dig a little. There are many speculations around this subject.

For a long time, crawlers could not understand them, but this is no longer the case. The most relevant answer I found was from this article and today’s conclusion seems to be:

Since search engines consider the content in iframes to belong to another website, the best you can hope for is no effect. Iframes tend to neither help nor hurt your search engine ranking.

Thus, it is best to assume that the content displayed via iframes may not be indexed or available to appear in Google’s search results. A workaround would be to make sure to provide additional text-based links to the content they display so that Googlebot can crawl and index this content.

Note : You should also not worry about duplicate content issues since today’s web crawlers usually recognize them.

Can iframes affect the loading speed of my website?

Every iframe on a page will increase the memory used as well as other computing resources like your bandwidth.

So, you should not use iframe excessively without monitoring what’s going on, or you might end up harming your page performance.

To avoid having your iframes slow down your pages, a good technique is to lazy load them (i.e., loading them only when they are required like when the user scrolls near them).

This can be achieved easily just by adding the loading="lazy" attribute to the tag.

Keep in mind that all modern Chromium-based browsers support this at the time of this writing. You will be interested in the lazyload library for something that works everywhere.

<iframe src="https://logrocket.com/" loading="lazy"></iframe>

Enter fullscreen mode

Exit fullscreen mode

Note : The loading="lazy" attribute also works with the img tag, in case you didn’t know that already.😜

How can I make an iframe responsive?

As more people browse the web using their phones, it is essential to make sure every one of your interfaces is responsive.

But how can you do so when you have an iframe in your page?

We could dedicate an entire guide regarding the myriad of ways to make your iframe responsive. Instead, I will just link to two excellent articles:

  • This first article (with probably the simplest solution) will show you how you can achieve this by wrapping your iframe in another HTML element and by adding a few CSS properties to it.

  • This second article will show you how you can make an iframe responsive by dealing with aspect ratios.

  • There is also the Iframe Resizer Library, but keep in mind that it comes with a lot of additional features you may not actually need.

Note : If you are using the bootstrap library in your project, there are the embed-responsive and embed-responsive-16by9 that you can use straight out of the box to make your iframes responsive.

<div class="embed-responsive embed-responsive-16by9">
  <iframe src="https://logrocket.com/" loading="lazy"></iframe>
</div>

Enter fullscreen mode

Exit fullscreen mode

How to prevent the white flash that occurs while the iframe is loading

Yes my friends, there is a solution for this. In this article, Chris Coyier shares a little snippet that hides all the iframes on the page with some CSS and removes it until the window is loaded and then makes them visible.

How to reload the content of an iframe

Easy peasy lemon squeezy! As you can access the window element of the iframe with contentWindow, you have to do this:

// Get the iframe
const iframe = document.getElementById('myIframe');

// Reload the iframe
iframe.contentWindow.location.reload();

Enter fullscreen mode

Exit fullscreen mode

I hope this guide has helped you to improve your knowledge of iframes.

While they can be insecure if you’re loading untrusted content, they also offer some significant advantages. So you should not ban them entirely from your developing arsenal but only use them in relevant situations.

If you have anything to add to this article, you can reach me in the comments below or just ping me on Twitter @RifkiNada


Plug: LogRocket, a DVR for web apps

 

LogRocket Dashboard Free Trial Banner

 
LogRocket is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

 
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

 
Try it for free.


The post The ultimate guide to iframes appeared first on LogRocket Blog.

Понравилась статья? Поделить с друзьями:
  • Ifh 0018 initialization error inpa ошибка
  • Ifh 0009 ошибка inpa
  • If0 ошибка электролюкс посудомойка
  • If you continue to receive this error message contact the hardware manufacturer перевод
  • If you are the redmine administrator check your log files for details about the error