Execute the injected JavaScript script after the WKWebView web page has completed loading

I need a solution to ensure that a specific script in WKWebView only runs once the webpage is fully loaded, including images. Currently, I've tried executing the function

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
and calling
self.webView.evaluateJavaScript(...)
within didFinish. However, I have observed that didFinish activates before the webpage finishes loading. In order to run my code accurately, I have resorted to using
DispatchQueue.main.asyncAfter(deadline: .now() + 0.6)
to delay the function execution, allowing sufficient time for the content to download. Nevertheless, I am seeking a more reliable approach as this method may not be suitable if there are slow WiFi connections causing the function to trigger prematurely.

Is there a way to delay the execution of webView.evaluateJavaScript(...) until the entire webpage has finished loading?

The following snippet represents my failed attempts:

self.webView.evaluateJavaScript("function getHTML() { return document.documentElement.innerHTML; } window.onload = getHTML", completionHandler: { (html: Any?, error: Error?) in`

Any assistance provided will be greatly appreciated!

Answer №1

Starting with creating a WkUserScript for your script is a good approach -

let myScript = WKUserScript(
        source: yourScript,
        injectionTime: WKUserScriptInjectionTime.atDocumentEnd,
        forMainFrameOnly: true
    )

Next, incorporate it into WKUserContentController like so -

let contentController = WKUserContentController()
contentController.addUserScript(myScript)

Then, set up the WKWebViewConfiguration with the userContentController -

let webViewConfig = WKWebViewConfiguration()
webViewConfig.userContentController = contentController

Lastly, include this configuration in your webView during initialization -

let webView = WKWebView(frame: boundsOfYourWebViewOutlet, configuration: webViewConfig)

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

The value in the input will not be refreshed

Hey there, I've been struggling to make this script work and I can't seem to pinpoint the issue. The goal is to use tinyMCE along with jQuery dialogue to take input from 2 fields and then output it in a specific format. Here's the code snipp ...

Having trouble getting haxe-pixi.js to function properly as it only shows a blank white screen

***UPDATE: Success! Managed to solve the issue. It turns out the missing library in the html file was causing the problem. The pixi.min.js file was not present in the haxelib directory, which seems a bit unusual. Here's a more challenging question: i ...

Is it possible to execute a function before or after each method of a factory or class is called in AngularJS or JavaScript?

In various programming languages such as Java, Ruby, and others, there is often a functionality to call a function before or after a method is executed. This feature is commonly provided by the frameworks being used. For example, Jasmine (a unit-testing li ...

Updating the color of tick marks on checkboxes

I have successfully updated the background color of my checkboxes using a custom function. However, the tick mark on the checkbox now turns black instead of remaining white. How can I keep the tick mark white while changing the background color? Here is t ...

Laravel-Mix and BrowserSync are all set up and running smoothly, but there seems to be a glitch

tag, I have some important details regarding my current setup: [email protected] Node v12.16.2 NPM v6.14.4 Operating System: Laravel Homestead Description: While running npm run watch, everything seems to work smoothly. Updates on views, cont ...

Modifying the data received from a service also updates the data within the service itself

After storing data received from a service in my controller and making edits, I noticed that the changes also reflect back in the original data stored in the service. JSFiddle Demo /* Omitted backend connection section and markdown editor JS code for br ...

Invoke ajax.fail() within the ajax.success() method

Is there a way to conditionally trigger the .fail method from within the .success callback? var myAjaxCall = $.ajax({ url: myUrl, type: "POST", data: myData, dataType: "json", processData: false, contentType: "application/json; c ...

What could be the reason for setTimeout not activating at the set time?

I'm currently experimenting with a simple JavaScript code in Visual Studio Code, but I seem to be having issues with the callback function not getting triggered. My main focus is on understanding the functionality of setTimeout() in JavaScript. I hav ...

There appears to be a malfunction with WebRupee

I have incorporated the new rupee sign into my website to represent Indian currency. Below is the code snippet I used: For the script, I included " and also added the following: <span class="WebRupee">Rs.</span> 116,754.00 To style it using ...

iOS Swift 3: Implementing Repeated Local Notifications on Selected Days of the Week

I'm in the process of developing my very first app that allows users to create alerts for themselves, with the app sending a local notification at the specified time. However, I'm facing a challenge in setting up the local notification to trigger ...

What steps do I need to take to implement AJAX form authentication?

I have set up a login screen that validates username and password credentials through a php script. When a user enters their information and submits the form, the authenticate.php file executes an LDAP bind. If the credentials are correct, the user is redi ...

Utilizing objects as tags within the Form Tags component in Bootstrap Vue

Let's break down the following code snippet from the documentation: <template> <div> <b-form-tags v-model="value" no-outer-focus class="mb-2"> <template v-slot="{ tags, inputAttrs, inputHandlers, addTag, removeTag }"> ...

Using AngularJS $http to retrieve data from an ExpressJS endpoint: A comprehensive guide

Here is an example of an ExpressJS route: var exec = require('child_process').exec; app.get('/someURL', function (req, res) { exec('cp file1 file2', (err, stdout, stderr) => { if (err) { // node co ...

Error encountered in Javascript security

Recently, I set up a local web server using node.js (watch-http-server). Everything runs smoothly when I test it within Stack's snippet. However, I encountered an issue when attempting to run it on the actual local web. SecurityError: Permission deni ...

Utilizing Jquery for Selecting Multiple Classes and Importing External Content

I'm faced with a challenge involving 2 links, both having the class dynamicLoad. <ul class="navbar"> <li><a href="Page3-News.html" class="dynamicLoad news">NEWS</a></li> <li><a href="Page2-Events.html" ...

Achieving secure HTTPS connection with socket.io

At the moment, my setup involves: let connectTo = "http://myip:myport"; var socket = io.connect(connectTo, {secure: true}); on the client side and const port = myport; const io = require('socket.io')(port); on the server side. I am looking to ...

Manipulating specific elements within a MongoDB document's array using index values in a Node.js environment

Is there a way to increase the value of a specific element in an array within a MongoDB document using Meteor or nodeJS? For example, consider the following document: { "_id" : "4tP6ewe4Z5kwYA3Je", "name" : "chutia", "address" : "shonir akhra ...

I'm encountering an issue in JavaScript while attempting to convert the following string into a JSON object. Can anyone assist in identifying the problem with this string?

How can I correct this string to make it a valid JavaScript JSON object? txt = '{"Categories" : [{"label":"petifores","id":"1"}, {"label":"wedding cake","id":"2"}, {"label":"shapes of cakes","id":"3"}, ...

Is it possible to utilize the provisioning profile for both the Enterprise store and App store?

I need advice on distributing my iOS app. It's currently in the Enterprise store, but I also want to release it on the App Store. Can I use the same certificate and provisioning profile for both versions, or will I need to create new ones? And what ab ...

Error: The term "OrbitControls" is not recognized in the three

When attempting to import OrbitControls.js, I encounter the following issue: The error message Cannot use import statement outside a module is displayed. To resolve this, I add: <script type="module" src="OrbitControls.js">< ...