Home > Software design >  Changing and loading an iframes src when the link within a file changes/updates
Changing and loading an iframes src when the link within a file changes/updates

Time:10-14

I'm building a page called live_link_frame.php and within it is loading an iframe via a url pulled from a local file: live_link.txt:

<?php
$filePath = 'live_link.txt';
$handle = @fopen($filePath, "r");
$text = fread($handle,filesize($filePath));
$lines = explode(PHP_EOL,$text);
$live_link = reset($lines);
?>

and

<iframe src="<?php echo "$live_link"; ?>"></iframe>

Is there a way to have the iframe src= update with the new value from $live_link when the url is changed in the local file? It doesn't have to be isolated to just php.

Everything I've tried so far ends up being some kind of looping method and causes the live_link_frame.php page to never fully load.

CodePudding user response:

This can be achieved with Javascript:

In your index page, you have some javascript that periodically checks inside live_link.php. You change the value in the makeInterval function to how often you want the file to be checked, 10000 = 10 seconds.

<script>
function makeInterval()
{
    getFileAndSetIframe();

    let interval = setInterval(getFileAndSetIframe, 10000);
}

function getFileAndSetIframe()
{
    let current_src = document.getElementById('changeme').getAttribute('src');
    let link = fetch('live_link.php')
        .then(response => response.text())
        .then((response) => {
            if (response !== current_src) {
                document.getElementById('changeme').setAttribute('src', response);
            }
        });
}

window.addEventListener ? window.addEventListener("load",makeInterval,false) : window.attachEvent && window.attachEvent("onload",makeInterval);
</script>

<h1>This is my page</h1>

<iframe src="" id="changeme"></iframe>

Note that if the URLS are of external sites you will probably run into issues.

  • Related