Javascript поиск во фрейме

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

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

Более новая информация по этой теме находится на странице 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 нужно работать не с начальным документом, а с тем, который появится позже.

Читайте также:  Архив файлов java программ

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

Элемент является «двуличным». С одной стороны, это обычный узел 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 и формой. Ни то ни другое не сработает:

Источник

How TO — Get Iframe Elements

Get an element from within an iframe with JavaScript.

Click the button to hide the first H1 element in the iframe (another document).

Get Element in Iframe

Get the first element inside the iframe and hide it:

Example

var iframe = document.getElementById(«myFrame»);
var elmnt = iframe.contentWindow.document.getElementsByTagName(«H1»)[0];
elmnt.style.display = «none»;

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

How TO — Get Iframe Elements

Get an element from within an iframe with JavaScript.

Click the button to hide the first H1 element in the iframe (another document).

Get Element in Iframe

Get the first element inside the iframe and hide it:

Example

var iframe = document.getElementById(«myFrame»);
var elmnt = iframe.contentWindow.document.getElementsByTagName(«H1»)[0];
elmnt.style.display = «none»;

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

How to select an element inside a frame using javascript / Various ways to select an element inside a frame using javascript

Suppose you have an HTML page whose elements are embedded in a frame, how would you select them. For Example, assume that you have a page with following structure:

Now suppose you want to select the text box in frame1 using javascript. There are following ways by which this can be done :

Method 1 : Fetching element directly inside the frame Fetch the frame using frames property of window object. frames property returns an array of all frames inside the current window. A frame can then be accessed by using its index or by its name.

var frame = window.frames[‘frame1’];
var documentObj = frame.document;
var element = documentObj.getElementsByName(‘frame1Text’);

If you know the index or its position of a frame then it can also be accessed as window.frames[0]; . Index is 0-based. Note : frames property will also return all iframes inside a window object. Also, elements are not supported in HTML5.

Method 2 : Using contentWindow property Fetch the frame by its id or name and use its contentWindow property to get the document object associated with this frame. contentWindow property has a document property which returns the document object for the selected frame. Using this document object, you can easily play around with the elements inside it.

var element = document.getElementById(‘myframe1’).contentWindow.document.getElementById(‘frame1Text’)

var frame = document.getElementById(‘myframe1’);
var documentObj = frame.contentWindow.document;
var element = documentObj.getElementById(‘frame1Text’);

Method 3 : Using contentDocument property A frame object has a contentDocument property which directly returns the document associated to that frame. Using this document object, you can easily play around with the elements inside it.
contentDocument is a short way of getting a frame’s document object in comparison to contentWindow . Thus,

var frame = document.getElementById(‘myframe1’);
var documentObj = frame.contentDocument;
var element = documentObj.getElementById(‘frame1Text’);

  1. You can also fetch a frame by its name using getElementsByName method of document object. This method returns a collection since more than one element can have the same name on a page. Thus for interacting with the desired element, its index should also be used after the method as document.getElementsByName(«frame1»)[0] . Index is 0-based.
  2. document object is the root node of an HTML document.
  3. When we say a frame’s document, it means the root of frame since a frame is also an independent HTML document.

Share if it’s worth .

Источник

How to get element from an Iframe in JavaScript

In this tutorial, we are going to learn about how to get the html elements from an Iframe in JavaScript.

Consider we have a following element in our index.html file.

iframe id="myIframe" src="/index.html" width="500px" height="500px">/iframe>

Getting the element in Iframe

To get the element in an iframe, first we need access the element inside the JavaScript using the document.getElementById() method by passing iframe id as an argument.

const iframe = document.getElementById("myIframe");

Now, it has and contentWindow property which returns the document object by using that we can access the elements from an Iframe.

const iWindow = iframe.contentWindow; const iDocument = iWindow.document; // accessing the element const element = iDocument.getElementsByTagName("p")[0]; element.style.color = "green";

In the example above, we have accessed the first

element from an Iframe and changed its color to green .

Similarly, we can access and modify other elements in the iframe using document object.

Note: If you want to access an iframe, it should be on the same domain otherewise you can’t access it because of security reasons (like XSS).

Источник

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