Tips for detecting the creation of an iframe before executing any javascript code

Before executing some JavaScript, I am trying to wait for an iframe to be created. I have attempted several methods, but none seem to effectively wait for the iframe. The console error that keeps appearing is

Uncaught (in promise) TypeError: Cannot read properties of null (reading 'src')
.

The current code snippet below attempts to integrate the waitForElm function from this StackOverflow post, yet I continue to encounter the same error.

I require a value from within the iframe. Therefore, my goal is to wait for the iframe to load, retrieve the src of the iframe, utilize fetch() to make a call, parse it with DOMParser, and then extract the item barcode.

This task is related to the implementation of the Google Books Viewer API.

Additionally, I do not have direct access to the main HTML page or the iframe itself. As a result, for instance, the creation of a script tag for the Google Books API is carried out through a function.

Apologies if there are any basic errors in my JavaScript code as I am relatively new to this programming language.

// create a script tag to load the Google Books API
(function(){
const gb = document.createElement('script');
gb.type = 'text/javascript';
gb.src = 'https://www.google.com/books/jsapi.js';
gb.addEventListener('load', () => google.books.load());
document.head.appendChild(gb);
})();

//function to wait for iframe to load
function waitForElm(selector) {
return new Promise(resolve => {
  if (document.querySelector(selector)) {
      return resolve(document.querySelector(selector));
  }
  const observer = new MutationObserver(mutations => {
      if (document.querySelector(selector)) {
          resolve(document.querySelector(selector));
      }
  });
  observer.observe(document.body, {
      childList: true,
      subtree: true
  });
});
}



app.controller('prmAlmaMashupAfterController', [function() {
this.$onInit = async function() {
  const frame = document.querySelector("#iFrameResizer0");
  fetch(frame.src)
    .then(res => res.text())
    .then(text => new DOMParser().parseFromString(text, 'text/html'))
    .then(document => {
      const bCode = document.getElementsByClassName('itemBarcode')[0].innerText || '';
      if (bCode) {
        const canvas = document.getElementById('viewerCanvas');
        const viewer = new google.books.DefaultViewer(canvas);
        viewer.load('NLS:' + bCode);
    console.log(bCode);
      } else {
        console.log('No barcode');
      }
    })
    .catch( e => {
      console.log('ERROR', e);
    });
}
}]);

//create a div called viewerCanvas to hold the viewer
app.component('prmAlmaMashupAfter', {
bindings: { parentCtrl: '<' },
controller: 'prmAlmaMashupAfterController',
//  template: '<div id="viewerCanvas" style="height: 500px; width: 600px; border: 1px solid blue"></div>'
template: '<div id="viewerCanvas" style="height: 500px; width: 100%; margin: 1% auto !important;"></div>'
});

Answer №1

To ensure the iframe loads completely, you can use an event listener for the load event on the iframe element:

frame.addEventListener("load", function() {
  // action to take when loaded
});

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

Retrieve the selected option value from a dropdown menu when hovering or making a change within the same event

Apologies for my poor English. Is there a way to retrieve the value of a select box when a user either changes the select box or hovers over it with just one event? I attempted the following code snippet but it did not work as expected: jQuery("select[nam ...

Implement pop-up functionality on additional buttons. Modify existing code to accommodate multiple buttons

I have a feature that allows me to click on a button and trigger a pop-up window with the desired content. The issue I am facing is how to duplicate this functionality for multiple buttons, each triggering a different pop-up content. I attempted to duplic ...

Invoking AngularJS Function from Login Callback Script

Just getting started with angularjs and I have a logincallback function that is used for external login. This function returns the returnUrl, closes the externallogin pop up, and redirects back to the main page. function loginCallback(success, returnUrl) ...

Display a concealed text box upon clicking BOTH radio buttons as well as a button

Below is the HTML code for two radio buttons and a button: <body> <input data-image="small" type="radio" id="small" name="size" value="20" class="radios1"> <label for=&qu ...

What is the method for retrieving the data from an XMLHttpRequest response?

Is there a way to use jQuery to query the result of an XMLHttpRequest? For example, let's say I have this code snippet: $.get('somepage.htm', function(data) { console.log($("div.abc").text()); }); The issue is that $("div.abc").text() i ...

Error encountered when attempting to initiate a second screenshare on Chrome due to an invalid state

I am interested in utilizing Screensharing in Chrome. After following a guide and creating an extension to access the deviceId for getUserMedia, I was able to successfully start streaming my screen. However, when I attempted to stop the stream using the pr ...

The npm package for @azure/storage-blob doesn't seem to play nice with the Azure Blob storage modules for IoT Edge

Currently, I am developing an edge module using Node.js to interact with Azure Blob storage modules on IoT Edge platform. To achieve this, I am following the documentation available at https://www.npmjs.com/package/@azure/storage-blob. The npm package ut ...

I seem to be facing a challenge with retrieving results in my app when using mongoose - what could be causing this issue

mongoose.connect('mongodb://localhost:27017/codealong'); When I attempt to connect to MongoDB and post data, the process is successful but I do not receive any results in my browser. Instead, all I see is an empty square bracket [ ]. These are ...

Tips for utilizing the "this" keyword in JavaScript

Here's a snippet of code that I'm having trouble with: this.json.each(function(obj, index) { var li = new Element('li'); var a = new Element('a', { 'href': '#', 'rel': obj ...

Having trouble updating the route with the $location service, even after attempting to use $scope.apply

After trying to utilize the location service with no success, I am left wondering why my view isn't changing even after using either $scope.$apply() or $scope.apply. Prior to posting my question, I conducted thorough research on similar inquiries but ...

While trying to set up a development server in Firebase, I mistakenly deleted my build folder

I recently encountered an issue with my Firebase project. While trying to set up a development server for my existing React web app that is already in production, I ran into some unexpected problems. firebase use bizzy-book-dev firebase init firebase ...

Unable to bind knockout dropdownlist data during an ajax request

Trying to connect a dropdownlist in knockout with MVC 4. Below is the code snippet: Action public JsonResult GetUserTypes() { using (QuestApplicationEntities db = new QuestApplicationEntities()) { var usertypes = (from ...

Having trouble manipulating state in JavaScript for React Native?

Encountering an issue when attempting to use the setState function in React Native. Code Snippet import React from "react"; import { TextInput, Text, View, Button, Alert } from "react-native"; const UselessTextInput = () => { st ...

An error occurred stating: "The require function is not defined in AngularJS and nodeJS."

I have searched through various similar questions here on SO, but none seem to provide a solution that fits my specific case. I am relatively new to using angularjs and nodejs, and I am encountering an issue that has me stuck. My goal is to save the input ...

Compiling Directives in AngularJS for Faster Page Loading

I'm currently experiencing performance issues in my Angular application. The root cause seems to be the excessive use of a directive on a single page. Unfortunately, I don't have the time to break down this page into multiple sections. I am seek ...

Using HTML and JavaScript to implement a dragging functionality on a canvas element

After creating a square grid using HTML canvas, I've added a drag feature that allows users to draw rectangles by dragging over the grid. However, it seems that non-rectangle shapes can also be drawn in certain cases. Let's delve into an additio ...

Issue with creating a variable name inside a JavaScript for loop

Here is the code snippet I am currently working on: var var1 = 58; for(var i=0;i<10;i++){ if(("var"+i) == 58) { console.log("they are equal"); } } I am wondering why ("var" + i) is not equal to 58 in this scenario. Could someone please provide an ...

Using special characters in AngularJS ng-bind function

When trying to bind a field from the database using ng-bind, I encountered an issue with a field name such as XYZ/ABC. Using td ng-bind="XYZ/ABC", it prints out NaN. How can I escape the / in the field name while binding? Keep in mind that I am retrieving ...

Ways to transmit the appropriate model

Using AJAX, I am sending a model to the server via a POST request. I have defined a model and a controller method for processing it. public class TestDto: BaseDto { [Required] public ProductGalleryDto GalleryProduct { get; set; } public int ...

Learning to Use jQuery to Send JSON Requests in Rails

I am attempting to send a JSON post request to a Rails 3 server. Here is the AJAX request I have set up: $.ajax({ type: 'POST',<br> contentType: "application/json",<br> url: url, ...