Initiating iOS UIWebView when the DOM is fully loaded

One issue I'm facing is that UIWebView triggers webViewDidFinishLoad before its content is actually rendered, resulting in a short delay after the view is displayed before the content appears. I'm curious if there's a way to trigger an event when the DOM is completely rendered.

Answer №1

Indeed, utilizing JavaScript is the way to go. For your HTML page, include a window.onload JavaScript handler. Once it triggers, you have two options:

  1. Trigger a call to the application by loading a dummy URL and capturing it with the webview delegate. For example:

    //within your web page, using JavaScript
    
    window.onload = function() { document.location.href = 'http://example.com/load'};
    
    //webview delegate in cocoa
    
    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
    {
        NSURL *URL = [request URL];
        NSString *host = URL.host;
        if ([host isEqualToString:@"example.com"])
        {
            //the webview has finished loading, so display it
            webview.hidden = NO;
    
            return NO;
        }
        return YES;
    }
    
  2. Set a flag variable in your JavaScript code, then use a timer in the application to check the webview by calling stringByEvaluatingJavascriptFromString to see if the flag has been set yet.

    //within your web page, using JavaScript
    
    window.pageReady = false;
    window.onload = function() { window.pageReady = true; };
    
    //within a timer in your native app code
    
    if ([[webview stringByEvaluatingJavascriptFromString:@"window.pageReady"] isEqualToString:@"true"])
    {
         webview.hidden = NO;
    }
    

Answer №2

Give this a shot

@interface DisplayWebViewController : UIViewController <UIWebViewDelegate>
@property(nonatomic, weak) IBOutlet UIWebView *displayWebView;
@end

@implementation DisplayWebViewController {

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Perform setup after loading the view.

    self.displayWebView.delegate = self;

    NSLog(@"%@", self.webContent.url);
    NSURL *webURL = [NSURL URLWithString:@"http://example.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:webURL];
    [self.displayWebView loadRequest:request];
}


- (void)webViewDidFinishLoad:(UIWebView *)webView {
    if ([[webView stringByEvaluatingJavaScriptFromString:@"document.readyState"] isEqualToString:@"complete"]) {
        // The UIWebView has finished loading.
        NSLog(@"Document ready");

    }
}


@end

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

What strategies can I implement to prevent the JavaScript CallStack from becoming overloaded?

The code snippet below outlines the functionality achieved through JavaScript (specifically for a node.js COMET application): A request is sent to the server and held until there is a response. Upon receiving a response, the data is processed, and anothe ...

Report the error efficiently without terminating the process

I created a tool for users to submit data. If the submitted data does not pass validation (validation returns false), I need to respond with an error 500 status code to the user. The issue is that when I use res.status(500), it causes the program to exit ...

Enhancing ASP.NET MVC 5 Application with jQuery Validate: Implementing Submit Button Click Events

In the process of developing an ASP.NET MVC 5 application, I find myself faced with a dilemma. The current setup involves using the jQuery Validate plug-in that comes packaged with MVC applications. Upon clicking the "submit" button, jQuery Validate kicks ...

Working with React, with the choice of incorporating jsx or not

I am currently delving into the world of React and found myself able to run a simple app without using JSX. In my JavaScript file, I started with: class TestClass extends React.Component Do I really need to utilize JSX or can I just stick with JavaScript ...

How do webpack imports behave within a ReactJS project?

In my ReactJS project, I have utilized various 3rd party libraries such as lodash, d3, and more. Interestingly, I recently discovered that I did not explicitly write imports like import d3 from 'd3' or import _ from 'lodash' in all of ...

Nodejs encountering error message during file download captured by a developer

I am attempting to download a file from nodejs. If there is an error on the backend, I need to display a message on the front end. The issue is that I cannot seem to capture that message. I suspect there may be some issues related to using blob and json ...

Currently, I am attempting to retrieve text input through the use of AngularJS

Having trouble retrieving text input values using Angular JS? The console keeps showing undefined. <div ng-controller="favouritesController" class="col-xs-12 favList"> <input type="text" ng-model="newFav" ng-keyup= "add($event)" class="col-xs-1 ...

Adjust the size of a picture within a table view cell

Can someone help me resize an image in a table view cell? I'm new to programming and struggling with it. I have managed to get the image into the cell, but I need to resize it according to my requirements. If anyone is able to provide some code snipp ...

Listening to changes in a URL using JQuery

Is there a way to detect when the browser URL has been modified? I am facing the following situation: On my webpage, I have an iframe that changes its content and updates the browser's URL through JavaScript when a user interacts with it. However, no ...

Exploring ways to assign a value to an HTML element utilizing Jquery in combination with ASP.NET MVC 4 complex model information

Within an ASP.NET MVC 4 view, I am utilizing data from a Model to populate various HTML elements. The model is used in the view to showcase values like: <div>@Model.Category.Name</div> etc... However, there is a specific div tag <div id="D ...

Unlock the potential of Stripe's confirmCardSetup method when working with multiple elements in Laravel Cashier integrated with a Vue application. Master

Is it possible to send inputs separately from Stripe using the confirmCardSetup method, even though the documentation only mentions one cardElement element? https://stripe.com/docs/js/setup_intents/confirm_card_setup -> check the official documentation ...

(Solving the Issue of Size in Three.JS Transform Controls for Translation)

I have been working on customizing the transform controls in three.js for my current project. I successfully modified the rotation part and am now focusing on the translation aspect. In the translation Gizmo, there is an XYZ octahedron at the center. I hav ...

Using JQuery to find and update elements in the DOM

My goal with JQuery is to have the select attribute removed from the Default.aspx li element and added to the Feedback.aspx li element when a user clicks on a link like Feedback.aspx. <ul id="main_menu" class="main_menu ui-sortable"> < ...

Browsing through an array of objects in PHP

Currently working on creating an array of objects using jQuery. var selected_tests = $("#selected_tests").find("tr"); jsonLab = []; $.each(selected_tests, function() { jsonLab.push({ test: ($(this).children()).eq(0).text(), amount: ($(this).chil ...

Node -- error encountered: options parameter must be of type object

Encountering a frustrating issue with the error message TypeError: options must be an object. Currently delving into the State example in Chapter 4 of Node.js Design Patterns. Initially assumed it was a mistake on my end, but even after testing the file w ...

Webpack in Vuejs does not have access to the keys defined in dev.env.js file

The framework utilized here is vuejs-webpack, with build and config files located here. No modifications have been made to these files. According to the information on Environment Variables, the keys specified in dev.env.js should be accessible during the ...

Remove duplicate elements from a JSON array

How can I add each item in an array for each duplicate? Transform: [ { "uuid":"EE877ABD-932F-4B4C-AB23-B324363B0B60", "planning":[ { "uuid":"6D680178-9B05-4744-A004-163D4B3E1E84", "star ...

Encountering an error while configuring app.js with git bash

I am just starting out and eager to learn from scratch. I am trying to configure app.js in my sp-node-mysql folder to interact with MySQL using JavaScript. However, I seem to be stuck. Here is the code line in question: var mysql = require("mysql"); and ...

Update the document by sending the data and making changes based on the AJAX response

Currently, I am avoiding using jQuery and trying to work with the following code in PHP: <?php header ( 'Content-Type: text/xml; charset=utf-8' ); $con = @mysql_connect ( "localhost", "root", "" ) or die ( "Couldn't connect to database" ...

I am struggling to add a list from these nested functions in Express, but for some reason, the items are not being properly

I am currently working with three nested functions and facing an issue where the last function is not returning the desired list of items. Interestingly, when I log the results of the last function within the loop, I can see the URLs that I need. However, ...