Search code examples
javascriptiframegetelementbyidgetelementsbyname

document.getElementsByName returning NULL unless I view the HTML source


This seems like a simple problem but I just can't work it out.

Basically there's a website that we use at work which requires a lot of repetitive typing, so I was trying to make a tiny bit of JavaScript that would automatically put text into some of the websites fields. I was going to achieve this by making bookmarks that run the JavaScript code so I could have a few different ones depending on what I needed.

The issue is that whenever I do this it will just have an error because it returns NULL on the getElementsByName:

document.getElementsByName("user_name")[0].value=("Type Username Here");

Here's where I get confused though, it will work perfectly fine if I inspect the element and actually see the exact element that i'm trying to find, or when I view any of the source from the same area as it (what i'm trying to find is in a big iFrame). If I view just the base source it still won't work though.

I also tried using document.getElementById which has the exact same issue.

I'm running the code at the moment by pasting it into the Console on Chrome, so everything is loaded fine when I try to run the JavaScript.

If anyone has any suggestions it would be greatly appreciated.

TL;DR: JavaScript won't work unless I look at the HTML source.


Solution

  • what i'm trying to find is in a big iFrame

    The key part in accessing elements from the parent page (the page that has an iframe) to the child page (the page that's displayed within the iframe) is essentially this:

    bigIframe.contentWindow.document.getElementById('user_name')

    But there is some extra code to consider in order to build up to this point. The Plunker is a live demo, the Snippet features the key parts.

    PLUNKER

    SNIPPET

      <form id='form1' name='form1' action='' method='post' target='bigIframe'>
        <input id='inData' name='inData'>
        <input id='btn1' type='submit'>
    <!--iframe points to a blank because Snippet will not function correctly as a full functioning iframe for secrity reasons-->
        <iframe id='bigIframe' name='bigIframe' src='about:blank' width='400' height='300'></iframe>
      </form>
    
    <script>
      var form1 = document.getElementById('form1');
    
      form1.addEventListener('submit', function(e) {
        e.preventDefault();
        var bigI = document.getElementById('bigIframe');
        var data = document.getElementById('inData').value;
        var iUser = bigI.contentWindow.document.getElementById('user_name');
        iUser.value = data;
      }, false);
    </script>

    REFERENCES

    https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/contentWindow