Calling javascript function in iframe

Viewed 184144

I have problem calling a JavaScript function in an iframe from the parent page. Here is my two pages:

mainPage.html

<html>
<head>
    <title>MainPage</title>
    <script type="text/javascript">
        function Reset() 
        {
            if (document.all.resultFrame)
                alert("resultFrame found");
            else
                alert("resultFrame NOT found");

            if (typeof (document.all.resultFrame.Reset) == "function")
                document.all.resultFrame.Reset();
            else
                alert("resultFrame.Reset NOT found");
        }
    </script>
</head>
<body>
    MainPage<br>
    <input type="button" onclick="Reset()" value="Reset"><br><br>
    <iframe height="100" id="resultFrame" src="resultFrame.html"></iframe>
</body>
</html>

resultFrame.html

<html>
<head>
    <title>ResultPage</title>
    <script type="text/javascript">
        function Reset() 
        {
            alert("reset (in resultframe)");
        }
    </script>
</head>
<body>
    ResultPage
</body>
</html>

(I know that document.all isn't recommended but this page should only be viewed with IE internally and I don't think that's the problem)

When I press the Reset-button I get "resultFrame found" and "resultFrame.Reset NOT found". It seems to have a reference to the frame but can't call the function on the frame, why is that?

9 Answers

Calling a privacy-respecting XMLHttpRequest from an <iframe>

HTML:

<iframe id="iframe"></iframe>

JavaScript:

const iframe    = document.getElementById('iframe');
const iframeWin = iframe.contentWindow || iframe;
const iframeDoc = iframe.contentDocument || iframeWin.document;

let script = iframeDoc.createElement('SCRIPT');

script.append(`function sendWithoutOrigin(url) {
    let request = new XMLHttpRequest();

    request.open('GET', url);

    request.onreadystatechange = function() {
        if(request.readyState === XMLHttpRequest.DONE) {
            if(request.status === 200) {
                console.log('GET succeeded.');
            }
            else {
                console.warn('GET failed.');
            }
        }
    }
    request.send();
}`);

iframeDoc.documentElement.appendChild(script);

JavaScript evocation:

let url  = 'https://api.serivce.net/';
    url += '?api_key=' + api_write_key;
    url += '&field1=' + value;

iframeWin.sendWithoutOrigin(url);
Related