Updating embedded HTML within Iframes

Looking for a script that can dynamically change the src attribute of iframes at different intervals. The time between each change varies depending on the specific iframe.

For example: Page Loads Google.com is loaded. 15 seconds later Yahoo.com is loaded. 37 seconds later Ask.com is loaded. 12 seconds later Dogpile.com is loaded. and so on...

This is what I've attempted:

<html>

<head>
    <meta charset="utf-8" />
    <title>Monitor Presidency</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.js"></script>
</head>

<body>
    <div style="width: 100%; display: flex;">
        <div class="ui teal progress" data-percent="0" id="example1" style="width: 90%;margin-bottom: 0px">
            <div class="bar"></div>
        </div>

        <div class="ui icon buttons" style="width: 10%">
            <button class="ui button" style="width: 25%" onclick="subtract_one()">
                <i class="left chevron icon"></i>
            </button>
            <button class="ui button " style="width: 25%" onclick="start()">
                <i class="play icon"></i>
            </button>

            <button class="ui button" style="width: 25%" onclick="pause_application()">
                <i class="pause icon"></i>
            </button>

            <button class="ui button" style="width: 25%" onclick="add_one()">
                <i class="right chevron icon"></i>
            </button>
        </div>
    </div>


    <iframe id="container" class="frame_monitor" style="width: 100%;height: 100%;" src="www.google.com"></iframe>
    <iframe id="shipping_hl" class="frame_monitor" style="width: 100%;height: 100%;display: none;" src="www.yahoo.com"></iframe>
    <iframe id="shipping_hl_accumulated" class="frame_monitor" style="width: 100%;height: 100%;display: none;" src="www.terra.com"></iframe>



</body>
<script>
    var monitor_array = ["container", "shipping_hl", "shipping_hl_accumulated"];
    var current_monitor = 0;
    var progress = 0;
    var myVar;

    var setIntervalUpdateFrame;


    function add_one() {

        /*  if (current_monitor === 2) {
              current_monitor = 0;
          } else {
              current_monitor++;
          }

          $('.frame_monitor').css('display', 'none');
          document.getElementById(monitor_array[current_monitor]).style.display = "";*/

        progress = 100;
        stopFunction();
        start();
        /*  if (current_monitor === 2) {
              current_monitor = 0;
          } else {
              current_monitor++;
          }*/

    };

    function subtract_one() {
        //progresso = 100;

        if (current_monitor === 0) {
            current_monitor = 2;
        } else {
            current_monitor--;
        }

        $('.frame_monitor').css('display', 'none');
        document.getElementById(monitor_array[current_monitor]).style.display = "";
        progress = 0;
        stopFunction();
        start();


    };

    function start() {
        clearInterval(setIntervalUpdateFrame);

        stopFunction();
        myVar = setInterval(function () {
            if (progress === 100) {
                progress = 0;

                if (current_monitor === 2) {
                    location.reload();
                    //num_monitor = 0;
                } else {
                    current_monitor++;
                }
                $('.frame_monitor').css('display', 'none')
                document.getElementById(monitor_array[current_monitor]).style.display = "";
            };



            progress++;
            progress++;
            $('#example1').data('percent', progress);
            $('#example1').progress();
        }, 3800);
    }

    function stopFunction() {
        clearInterval(myVar);
        //atualiza_frame();
    }
    start();

    function pause_application(){
        clearInterval(myVar);
        update_frame();
    }

    function update_frame() {
        clearInterval(setIntervalUpdateFrame);
        setIntervalUpdateFrame = setInterval(function () {
            document.getElementById(monitor_array[current_monitor]).src=document.getElementById(monitor_array[current_monitor]).src;
        },1);
    }
</script>

</html>

Answer №1

  • The usage of setInterval and setTimeout in your code is not handled correctly, resulting in the creation of a timer id for scheduling executions. https://www.telerik.com/blogs/how-do-i-pause-execution-in-javascript
  • A more efficient approach would be to utilize the Promises async library, as demonstrated below. 1
  • Regarding websites that prevent framing through response headers, a workaround involves using a back-end program where the server loads and forwards web files. 2

    <!DOCTYPE html>
    <html>
      <head>
        <title> Hello </title>
        <style>
            iframe {
                display: block;
                width: 1000px;
                height: 500px;
                margin-left: auto;
                margin-right: auto;
              }
    
              iframe:focus {
                outline: none;
              }
    
              button {
                display: block;
                margin: auto auto;
              }
    
              label {
                display: block;
                margin-left: auto;
                margin-right: auto;
              }
    
              input {
                display: block;
                margin: auto auto;
              }
        </style>
      </head>
      <body>
        <div id='main'>
          <button id='wait' onclick='wait()'>Wait</button>
          <label>Seconds</label>
          <input type='number' id='seconds' placeholder='milliseconds'>
          <button id='switching' onclick='webSwitch()'>Switch sites</button>
          <iframe id='switchMe' src='https://codepen.io'></iframe>
        </div>
        <script>
          //Array of webpages
         var webList = ["https://www.bing.com", "https://www.walmart.com","https://www.codepen.io"];
         //For tracking position in array
         var count = 0;
    
         //Function to be ran by event
         function webSwitch() {
            console.log('I have been called');
           if (count >= webList.length) {
             count = 0;
           }
           //Setting new URL
           document.getElementById('switchMe').src = webList[count];
           //Make sure to use next URL
           count++;
         }
    
         function wait() {
            console.log('Click!');
            var numMS = document.getElementById('seconds').value;
            sleep(numMS).then(() => {
                webSwitch();
            })
         }
    
         function sleep (time) {
            return new Promise((resolve) => setTimeout(resolve, time));
         }
        </script>
      </body>
    </html>
    

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accessing a Child Component Function in Material UI

Utilizing the Material UI framework, I am constructing an application with React. Included in this application is a Dialog feature that permits users to modify various information about an object (referencing the code below). The dialog consists of two but ...

Retrieve JSON Data Using Angular in a Wordpress Environment

I need assistance with displaying a JSON Array in <li>'s within a Wordpress Template. Here is the specific JSON file: I am completely unfamiliar with how to achieve this. This is the HTML code I have: <div ng-app="appExtern" ng- ...

Tips for customizing the blinking cursor in a textarea

I am experimenting with creating a unique effect on my website. I have incorporated a textarea with transparent text overlaying a pre element that displays the typed text dynamically using JavaScript. This creates an illusion of the user typing in real-tim ...

Calculate the previous date excluding Sundays by subtracting the specified number of days from the given date

I'm experiencing an issue with this Date : 09/30/2014 NumOfDays : 5 Expected PreComputed Date : 09/24/2014 ---------------------------- 09/29/2014 Day 1 09/28/2014(Sunday) Skip 09/27/2014 Day 2 09/26/2014 Day 3 09 ...

Extracting information from Javascript on an HTML webpage

The text snippet provided is a segment of an HTML page. I am looking to extract the data but unsure about the most effective method to do so. JSON would be ideal, however, I am uncertain if this content can be converted into JSON format. Is Regular Expre ...

CSS-loader imported styles failing to function properly

Constructing a React 16.4.0 application with Bootstrap 4.1.1. My approach involves using css-loader alongside webpack to generate personalized stylesheets for each component within my app. Despite my efforts, I am facing the issue where my custom styles ...

Here's a unique rewrite of the text: "What is the best way to run a JavaScript script in Java and

Currently in the process of automating a web application that utilizes SmartClient, I am in need of a reliable method for constructing locators for forms and populating input fields. Our testing framework is based on Selenium and SmartClient's scLocat ...

What is the reason for the presence of "CTYPE" in my HTML upon refreshing the page?

As I am utilizing Harp and Bootstrap for my project, I am encountering a peculiar issue. Upon refreshing the page, I notice that the text ""CTYPE html>"" is inserted within the body tags. Can anyone shed light on why this is happening? ...

What is the solution for resolving the "cannot resolve" issue in CSS for an Angular project?

During a small project I was working on, I decided to add a background image to another image using CSS. Here is the code snippet: .child2 img { width: 200px; height: 200px; border-radius: 50%; background-image: url('./assets/images/imageb ...

Is there a way to include multiple div elements on a single page using React?

I am currently in the process of developing an e-commerce website and I am looking to display multiple items on the front end using React.js with Bootstrap as the CSS library. Below is the code snippet for my return div. How can I go about showcasing mul ...

Embed an HTML file within another HTML file

I'm having trouble trying to include an Html file into another Html file. Can anyone offer some assistance? <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" ...

Adding additional text will not render d3.js' output

I'm struggling with a simple issue here, My goal is to add a div to my svg element containing text. I have written the code for this and in the DOM, it shows that the svg has the correct class attached along with the desired text. However, the text i ...

Edge browser: Disable Ctrl + left click functionality

Can I stop Microsoft Edge from automatically opening a link in a new tab when I use Ctrl + Left click? I want to trigger my own event instead of the default behavior caused by Ctrl + Left click in Edge browser. ...

Switching the background image upon hover while incorporating a subtle fade transition in HTML and CSS

Is there a way to set two background images on a div and have them change when hovering with a fade effect? Similar to the example shown. .kid { max-width:50%; position:relative; } .kid img { display:block; opacity:1; height: auto; transition:.6s ease; ...

Having trouble with the rowNode functionality in PrimeNG TreeTable

I am currently utilizing the PrimeNG Treetable component from https://www.primefaces.org/primeng/#/treetable I seem to be encountering issues with retrieving data from the service. Below is a snippet of my code: HTML <p-treeTable [value]="temp"> & ...

What is the best way to ensure that the execution of "it" in mocha is paused until the internal promise of "it" is successfully resolved?

const promise = require('promise'); const {Builder, By, Key, until} = require('selenium-webdriver'); const test = require('selenium-webdriver/testing'); const chai = require('chai'); const getUrl = require('./wd ...

Issue encountered when attempting to alter the action attribute of a form: receiving an error message stating 'undefined is not a function'

I am attempting to dynamically set the action attribute of a form based on the button clicked in order to navigate away from a page. Once the action is updated, the form should be submitted and the new action carried out. Below is my jQuery function: fun ...

Oops! Smarty encountered a fatal error that wasn't caught

An error occurred while processing the template file "C:\xampp\htdocs\eventos\libs\templates\teste.tpl" on line 9. The error message states: Fatal error: Uncaught exception 'SmartyCompilerException' with message &apo ...

What is a more efficient approach to managing the response from an asynchronous call other than using setState?

Utilizing javascript async await, I have been making service calls to the server in componentDidMount or componentDidUpdate. However, when I need to pass the response data as props to other components, I find myself updating the component's state with ...

Enhancing web pages with a touch of JSP glow

Is there a tool out there that can beautify HTML code and handle JSP elements without any issues? I've been on the hunt for one but haven't had much luck. I'm not interested in an HTML validator, just something that can properly format the c ...