Control iframe content with javascript/html

前端 未结 2 1818
小鲜肉
小鲜肉 2020-12-06 07:25

Within my webpage I have an iframe like so:


相关标签:
2条回答
  • 2020-12-06 07:32

    Yes, if you give your iframe an ID, for example

    <iframe src="thispage.html" width="100%" height="600" frameBorder="2" id="MyIframe"></iframe>
    

    You can access the inner window like this:

    var iw = document.getElementById("MyIframe").contentWindow;
    

    So you can call its functions e.g.

    iw.theFunctionInsideIframe();
    

    And you can locate the DOM elements like

    var anElement = iw.document.getElmentByID("myDiv");
    
    0 讨论(0)
  • 2020-12-06 07:33

    Yes you can. Say your iframe's ID is 'myIFrame'

    <iframe id="myIFrame" src="thispage.html"
        width="100%" height="600"
        frameBorder="2">
    </iframe>
    

    Then, add the following in your JavaScript:

    // Get the iframe
    const iFrame = document.getElementById('myIFrame');
    
    // Let's say that you want to access a button with the ID `'myButton'`,
    // you can access via the following code:
    const buttonInIFrame = iFrame.contentWindow.document.getElementById('myButton');
    
    // If you need to call a function in the iframe, you can call it as follows:
    iFrame.contentWindow.yourFunction();
    

    Hope it helps :)

    0 讨论(0)
提交回复
热议问题