56

I have a webpage hosted online and I would like it to be possible that I could insert an IFRAME onto another webpage using some JavaScript.

How would this be the best way possible, that I just add my webpage URL to the JavaScript and that it work on all browsers?

Thanks

Tim
  • 2,589
  • 6
  • 34
  • 39

3 Answers3

126

You can use:

<script type="text/javascript">
    function prepareFrame() {
        var ifrm = document.createElement("iframe");
        ifrm.setAttribute("src", "http://google.com/");
        ifrm.style.width = "640px";
        ifrm.style.height = "480px";
        document.body.appendChild(ifrm);
    }
</script> 

also check basics of the iFrame element

radiovisual
  • 6,298
  • 1
  • 26
  • 41
Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91
4

It is better to process HTML as a template than to build nodes via JavaScript (HTML is not XML after all.) You can keep your IFRAME's HTML syntax clean by using a template and then appending the template's contents into another DIV.

<div id="placeholder"></div>

<script id="iframeTemplate" type="text/html">
    <iframe src="...">
        <!-- replace this line with alternate content -->
    </iframe>
</script>

<script type="text/javascript">
var element,
    html,
    template;

element = document.getElementById("placeholder");
template = document.getElementById("iframeTemplate");
html = template.innerHTML;

element.innerHTML = html;
</script>
rxgx
  • 5,089
  • 2
  • 35
  • 43
-1

so I tried to put an embed youtube video to my index.html using google console API key, and this is the function that I made:

const searchVideos = async (key, search, maxResVideos) => {
    const config = { params: { key: key, q: search } }
    let res = await axios.get(`https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&maxResVideos=${maxResVideos}`, config);
    console.log('res:', res.data.items);
    res.data.items.forEach(item => {

        const video = document.createElement('div');
        video.innerHTML = `<iframe width="560" height="315" src="https://www.youtube.com/embed/${item.id.videoId}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`;
        searchResult.appendChild(video);
    });
}

you can still make changes but this puts the embed video by creating a div and putting the iframe as string template literals ...

kolpaja
  • 9
  • 2