Identifying modifications in WebView URL using Swift

I've been working on a hybrid app and I'm looking for a way to transfer data from the WebView to the native application.

My current approach involves using URL variables, and then setting up a listener in Swift to receive the new data.

So far, I've managed to extract the URL variable from the WebView when it initially loads using the following Swift code...

func webViewDidFinishLoad(_ webView: UIWebView) {

   print(getQueryStringParameter(url: (webView.request?.url?.absoluteString)!, param: "id"));

}
func getQueryStringParameter(url: String, param: String) -> String? {
    guard let url = URLComponents(string: url) else { return nil }
    return url.queryItems?.first(where: { $0.name == param })?.value
}


While this method is effective, I haven't been able to find a WebView listener that can detect when a new URL variable is added through JavaScript at a later point after the page has loaded. Here's the JS code I'm using...

window.history.replaceState(null, null, "?id=mydata");

Do you have any suggestions on how I can listen for this change in Swift? Or perhaps there's a better alternative for passing data from a web view to a native app?

Answer №1

If you want to achieve your goal, you can utilize this code snippet.

Make sure to utilize WKWebView and handle the appropriate delegates in order to complete the task.

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("Loading finished")
        if webView.url!.absoluteString.range(of: "ADD_STRING_TO_BE_VERIFIED_HERE") != nil
        {
            print("Task completed successfully")

            //EXECUTE YOUR FUNCTIONS HERE
        }
    }

I hope this solution is helpful for you...

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 is the easiest and most straightforward method for deploying HTML and JavaScript in Service Mix?

I am currently working on a small HTML/web page project and I am interested in deploying service mix. Although I have knowledge of the web page side and I am familiar with service mix, I haven't ventured into using a simple HTML/JavaScript setup withi ...

What is the relationship between $.when, apply(), and $.done() within the scope of this function?

I recently received this function from a helpful SO user that allows for returning a variable number of jQuery $.get() requests. The initial part seems pretty straightforward, but I am struggling to understand how $.when(), apply(), and $.done() are inte ...

Learn the process of dynamically loading scripts and their functions in Angular

At first, I had the following code statically placed in Index.html and it was functional. <script src="/le.min.js"></script> <script> LE.init({ token: 'token', region: 'x' }); </script> ...

Retrieve the URL of a particular XML document from the server using a PHP script, then dynamically load it into a JavaScript file for further processing

As I work on my website, users have the ability to upload and download files while I generate an XML log with operation details. One page on the site displays a table created by reading this XML log. Everything functioned properly when it was all stored l ...

conceal the mustard-colored dots within the overlay

Whenever I trigger the link, a modal window pops up, but it comes with an unwanted black background color and yellow dots. How can I prevent the yellow dots from showing up on the overlay? http://jsfiddle.net/y88WX/18/embedded/result/ <nav class="da-d ...

How to utilize a parameter value as the name of an array in Jquery

I am encountering an issue with the following lines of code: $(document).ready(function () { getJsonDataToSelect("ajax/json/assi.hotel.json", '#assi_hotel', 'hotelName'); }); function getJsonDataToSelect(url, id, key){ ...

Simplify your code with promises in JavaScript

Running on an API with node v6.3.0, I have the following code that executes two separate promises based on a conditional check for a parameter in a POST request. if (paramExists) { // query database with this condition User.filter(/* utilize param ...

Encountering issues with configuring an Express server with HTTPS

Having difficulty setting up my Express server on HTTPS and accessing my API. Below is the code I am using: // server.js const express = require('express'); const { readFileSync } = require('fs'); const https = require('https' ...

Having trouble with my JavaScript code in Visual Studio because of a bundler issue. It's throwing an Uncaught ReferenceError for trying to access a variable before initialization

My AJAX request looks like this: $.ajax({ method: 'GET', url: '/api/some-data', headers: { 'Content-Type': 'application/json' }, success: function(data) { if (data != null) { var userDat ...

IntelliJ Community offers comprehensive support for React.js development

Looking for a free React.js plugin with features like syntax highlighting and autocomplete that can be used in IntelliJ Community edition. Considering migrating from Ultimate license to Community edition. Found some answers on stackoverflow but none were ...

What is the process for sending a URL as a parameter to APIController using an AJAX request?

I'm facing an issue while attempting to pass a URL as a string parameter to the API Controller POST method. The error 'Potentially dangerous request' is being triggered due to the presence of special character ':' in the URL. The ...

Stop the ThreeJS rendering process

Currently, I am using ThreeJS to create a basic 3D scene with OrbitControls. The problem I'm facing is that it causes my entire website to lag, even when the user is not actively looking at the scene. I am in need of a function that can start and stop ...

Exploring Database with NodeJS, Express, and HTML

My goal is to create a basic web application using node.js where users can input data into a search bar and have that input sent to the server for database query. While I've successfully set up and connected my database, here's a glimpse of my co ...

Error: The post method in $setup is not defined in Vue Composition API

Dealing with a frustrating issue in my Vue application. One page is functioning perfectly fine, while the other is causing trouble by displaying this error: The first page loads a collection of wordpress posts (Blog.vue) without any issues, but the second ...

The CustomValidator ClientValidationFunction will only activate on the second or subsequent submission if CheckBoxList is checked

I am encountering an issue with a user control that is dynamically added to pages on DNN. The user control is built on a customized version of CheckBoxList and includes a CustomValidator with ClientValidationFunction set to a javascript function. It works ...

Crafting callback functions

My jQuery code looks like this: $('#current_image').fadeOut(function(){ $('#current_image').attr('src',newImage).show(); }); This process is wonderful - the nested function runs smoothly after the fadeOut. I ...

Nuxt.js is throwing a TypeError because it is unable to access the 'minify' property since it is undefined

When I try to generate a Nuxt app using "npm run generate" or "npm run build", I encounter an issue where it throws a TypeError: Cannot read property 'minify' of undefined. Does anyone know how to solve this? TypeError: Cannot read property &apo ...

Contrasting onevent with addEventListener

After studying various DOM events, I attempted to implement the 'blur' event on the HTML body. My first attempt was with onblur document.body.onblur = () => { dosomething(); } and I also tried using AddEventListener document.body.addEven ...

What is the best way to have my transparent navigation bar float on top of my background in a parallax-scrolling website?

Currently, I am working on creating a website with a navigation bar that has no background and floats on top of a background image. However, I am facing an issue with my parallax-scrolling website. Whenever the page is scrolled to the second section, the n ...

Verifying API access with custom settings using the got module

I'm having some trouble with a basic API call that requires authentication using the got library. I tried using the options parameter to pass my username and password, but I keep getting an HTTPerror. Could someone please review my usage of the optio ...