Javascript load in frame

How to get javascript in one frame to wait until a page has loaded in a second frame

and then performs actions on that page, for example searching text within the page. I need the script to wait until page.html has loaded in the second frame before doing this, and I can’t use onload=. in the second page because I have no control over its source. Is there a way to do this?

3 Answers 3

use onload event of FRAME element

or if you load different pages to the same frame use this:

Could you expand on that? If I use top.frames[1].location.href = ‘ongar.org/mypage.html’; top.frames[1].onload(alert(‘loaded’)); I get the alert before mypage.html has loaded, because there is already a page in frame[1]. I’d like the alert after mypage.html has fully loaded.

True, but in the example above you missed out the clause checking the location.pathname value of the new page.

onload events in iframes are sort of useless- they are very inconsistent across browsers, even within a browser understanding why onload is firing can be messy. Use with caution!

Читайте также:  Javascript load javascript dynamic

Well I do this, and it works.

var idInterval; function callPage() < top.main.document.location.href = somepage.aspx; document.getElementById('divLoading').style.visibility ="visible"; idInterval = setInterval("validaFrameMain()",50); >//look if the frame page is complete load function validaFrameMain() < if (top.main.document.readyState != "complete") else < document.getElementById('divLoading').style.visibility ="hidden";; clearInterval(idInterval); idInterval = nothing; >>

If you have no control over the loaded page’s source and more importantly, if it is coming from another domain, then there is only one answer:

Interframe communication between different domains is NOT possible. And you need interframe communication because you would need something like jquery’s ready function in the loaded page to determine if the entire page (the DOM) is loaded.

Источник

Общение между окнами и фреймами

Материал на этой странице устарел, поэтому скрыт из оглавления сайта.

Более новая информация по этой теме находится на странице https://learn.javascript.ru/cross-window-communication.

Элемент iframe является обычным узлом DOM, как и любой другой. Существенное отличие – в том, что с ним связан объект window внутреннего окна. Он доступен по ссылке iframe.contentWindow .

Таким образом, iframe.contentWindow.document будет внутренним документом, iframe.contentWindow.document.body – его и так далее.

В старых браузерах использовались другие свойства, такие как iframe.contentDocument и даже iframe.document , но они давно не нужны.

Переход внутрь ифрейма

В примере ниже JavaScript получает документ внутри ифрейма и модифицирует его:

  var iframe = document.getElementsByTagName('iframe')[0]; var iframeDoc = iframe.contentWindow.document; if (iframeDoc.readyState == 'complete') < iframeDoc.body.style.backgroundColor = 'green'; >iframe.onload = function() 

Атрибут src может использовать протокол javascript , как указано выше: src=»javascript:код» . При этом код выполняется и его результат будет содержимым ифрейма. Этот способ описан в стандарте и поддерживается всеми браузерами.

Атрибут src является обязательным, и его отсутствие может привести к проблемам, вплоть до игнорирования ифрейма браузером. Чтобы ничего не загружать в ифрейм, можно указать пустую строку: src=»javascript:»» или специальную страницу: src=»about:blank» .

В некоторых браузерах (Chrome) пример выше покажет iframe зелёным. А в некоторых (Firefox) – оранжевым.

Дело в том, что, когда iframe только создан, документ в нём обычно ещё не загружен.

При обычных значениях iframe src=»https://learn.javascript.ru/» , которые указывают на HTML-страницу (даже если она уже в кеше), это всегда так. Документ, который в iframe на момент срабатывания скрипта iframeDoc – временный, он будет заменён на новый очень скоро. И работать надо уже с новым документом iframeDoc2 – например, по событию iframe.onload .

В случае с javascript -протоколом, по идее, ифрейм уже загружен, и тогда onload у него уже не будет. Но здесь мнения браузеров расходятся, некоторые (Firefox) всё равно «подгрузят» документ позже. Поэтому факт «готовности» документа в скрипте проверяется через iframeDoc.readyState .

Ещё раз заметим, что при обычных URL в качестве src нужно работать не с начальным документом, а с тем, который появится позже.

Кросс-доменность: ограничение доступа к окну

Элемент является «двуличным». С одной стороны, это обычный узел DOM, с другой – внутри находится окно, которое может иметь совершенно другой URL, содержать независимый документ из другого источника.

Внешний документ имеет полный доступ к как к DOM-узлу. А вот к окну – если они с одного источника.

Это приводит к забавным последствиям. Например, чтобы узнать об окончании загрузки , мы можем повесить обработчик iframe.onload . По сути, это то же самое что iframe.contentWindow.onload , но его мы можем поставить лишь в случае, если окно с того же источника.

  

Если бы в примере выше был с текущего сайта, то оба обработчика сработали бы.

Иерархия window.frames

Альтернативный способ доступа к окну ифрейма – это получить его из коллекции window.frames .

Обратим внимание: в коллекции хранится именно окно ( contentWindow ), а не DOM-элемент.

Демонстрация всех способов доступа к окну:

   

Внутри ифрейма могут быть свои вложенные ифреймы. Всё это вместе образует иерархию.

Ссылки для навигации по ней:

  • window.frames – коллекция «детей» (вложенных ифреймов)
  • window.parent – содержит ссылку на родительское окно, позволяет обратиться к нему из ифрейма. Всегда верно:
// (из окна со фреймом) window.frames[0].parent === window; // true
window.frames[0].frames[0].frames[0].top === window

Свойство top позволяет легко проверить, во фрейме ли находится текущий документ:

Песочница sandbox

Атрибут sandbox позволяет построить «песочницу» вокруг ифрейма, запретив ему выполнять ряд действий.

  • Заставляет браузер считать ифрейм загруженным с другого источника, так что он и внешнее окно больше не могут обращаться к переменным друг друга.
  • Отключает формы и скрипты в ифрейме.
  • Запрещает менять parent.location из ифрейма.

Пример ниже загружает в документ с JavaScript и формой. Ни то ни другое не сработает:

Источник

Implement an onload Event in iframe in JavaScript

Implement an onload Event in iframe in JavaScript

  1. Execute a JavaScript Function on a Load of an iFrame
  2. Implement on load Event in iframe Using Pure JavaScript
  3. Implement on load Event in iframe Using onload Event Listner
  4. Use Inline Function in HTML’s onload Event Handler of iframe

stands for The Inline Frame Element. These are windows to load other web pages on our website and interact with them. The sites or webpages loaded using iframe maintain their session history and cache values and are not dependent on the parent or the calling browser screen. At times we may need to execute a function once the iFrame content has loaded. Let us look at ways in JavaScript to run a method once the iframe content is loaded.

Execute a JavaScript Function on a Load of an iFrame

We can use the onload event handler of the iframe HTML tag. The event fires once all the elements in the iframe is loaded. These include a loading of scripts, images, links, subframes etc. It accepts a function declaration as a parameter that we mention in the HTML tag. The onload=»siteLoaded()» will execute the siteLoaded() function, a simple JavaScript function that logs a text to the web browser console. Refer to the following code.

iframe src="https://www.youtube.com/" onload="siteLoaded()">iframe> 
function siteLoaded()   console.log("iframe content loaded"); > 

Implement on load Event in iframe Using Pure JavaScript

Another way to execute a JavaScript function once the loading of an iframe is complete is by using the onload event handler of JavaScript. For this, we query for the intended HTML element and attach the JavaScript function on the onload event handler of the HTML element. It is similar to the way we explained in the previous section. The difference is that we are using a pure JavaScript approach here called the Unobtrusive JavaScript. The HTML is kept lean and clean. Let us look at the following code to understand better.

iframe src="https://www.youtube.com/">iframe> 
document.querySelector("iframe").addEventListener( "load", function()   console.log("iframe content loaded"); > ); 

Executing this code may cause an error saying that JavaScript cannot add a listener to a null object. For that, we will need to wrap the code inside the window.onload method. Refer to the following code snippet.

window.onload = function()   document.querySelector("iframe").addEventListener( "load", function()   console.log("iframe content loaded");  > ); > 

JavaScript executes the window.onload function once it loads all the elements of the window . The addEventListener() function of JavaScript links a event listener to the HTML object. We first need to select the HTML object in which we intend to add the event listener. The document.querySelector() returns an HTML object, on this object we attach the load event listener with .addEventListener() function. The addEventListener() attaches a function, here an inline function, that is triggered once the iframe element is loaded. We can add a wide range of events to an HTML element using the addEventListener() function. But for the scope of our discussion, we will focus on the load event. Similarly, we can also add the click event to an HTML object.

Implement on load Event in iframe Using onload Event Listner

Like the .addEventListener() , we can also go for the onload event. Here too, we select the iframe element using functions like the document.getElementById() or document.querySelector() . Once the element is selected, we attach a JavaScript function to it. It also can be done in a couple of ways. One way is where we pass the function inline. And another way is to attach the function object without using the () . If we use () , JavaScript will execute the function at the first run instance itself. In JavaScript, we use the onload for its purpose alone, unlike the .addEventListener() , which is more generic. Refer to the following code to understand the usage of the onload function.

iframe id="my_iframe" src="https://www.youtube.com/">iframe> 
window.onload = function()   document.getElementById('my_iframe').onload = function()   console.log("iframe content loaded");  >; > 

We encapsulate the document.getElementById(‘my_iframe’).onload code section inside the window.onload , just to make sure that JavaScript is able to query the element. The window.onload ensures all the elements are loaded and are available for document.getElementById(‘my_iframe’) to fetch them. Once the element is queried, we attach the function to it using the onload event handler of the HTML object.

Use Inline Function in HTML’s onload Event Handler of iframe

Another way to execute a function on the load event is by attaching an inline method in the HTML. Though this is not the recommended way of implementing a JavaScript function on load events, it comes in handy as a hack at times of dire need. In this approach, we pass the method inline in the HTML in the onload function attribute of the iframe element. JavaScript will execute the function once the iframe is ready. Refer to the following code to understand the usage.

iframe src="https://www.youtube.com/" onload="(function()< console.log('iFrame Loaded'); >)();">iframe> 

Observe the way we write the function call in the onload event handler. The inline function call is enclosed in () . And there is a () following the inline function call. It is similar to attaching a function declaration in the onclick event for a div.

Related Article — JavaScript Event

Источник

Оцените статью