3

Apparently it's possible to access the iframe DOM object by name once you give it a 'name' attribute. If you type the name in chrome dev tools console, it will register the iframe object in the console.

That way you can also call JS methods from that iframe (see the onclick handler below).

How does it work? I mean, I thought name attribute only matters when it comes to forms - the server then is able to correctly read different fields that were set with a POST method for example. But here it makes a difference on the client side - it gives the ability to access the iframe and its functions. Does it work with iframes only? (If you try to get the code below to work locally you might get some errors, such as 'Blocked a frame with origin "null" from accessing a cross-origin frame', but I have a production code that does exactly that and it works fine.

.

<html>
<body>

<button id="fooButton" onclick="fooFrame.foo()">Click
</button>

<iframe id="fooFrame" name="fooFrame" src="./content.html">
</iframe>

<script>
console.log(fooFrame);
</script>
</body>
</html>
user5539357
  • 1,024
  • 1
  • 9
  • 19

1 Answers1

4

You can reference any element by it's name attribute with these methods:

.getElementsByName('NAME')

.querySelector('[name=NAME]')

.querySelectorAll('[name=NAME]')

Details are commented in Snippet

SNIPPET

/* Use a CSS selector to reference the first element */
var ifrm1 = document.querySelector('[name=ifrm1]');

/* Collect all elements by a name */
var iframes = document.getElementsByName('ifrm');

/* Collect a single element by a name (bracketed index[0])*/
var iframes0 = document.querySelectorAll('[name=ifrm]')[0];


ifrm1.style.borderColor = 'blue';

/* .getElementsByName() and querySelectorAll() return HTML Collections/NodeLists */
/* Any NodeList/HTML Collection should be iterated thru by a loop, an Array method, etc. */

var qty = iframes.length;

for (let i = 0; i < qty; i++) {
  iframes[i].style.backgroundColor = 'red';
}

/* .getElementsByName() and .querySelectorAll() can be used for a single element without iteration by using the bracket notation (ex. [0] is the first element in a collection/list*/

iframes0.style.borderColor = 'lime';
<html>

<body>


  <iframe name="ifrm1" src="about:blank"></iframe>

  <iframe name="ifrm" src="about:blank"></iframe>
  <iframe name="ifrm" src="about:blank"></iframe>
  <iframe name="ifrm" src="about:blank"></iframe>


</body>

</html>
zer00ne
  • 41,936
  • 6
  • 41
  • 68