Is there a way to use JavaScript to close WKWebView on a website?

I am facing an issue with implementing the closure of VKWebView upon registration in my completed application. This is something new to me and I haven't encountered it before.

WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];

        WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:theConfiguration];
        webView.navigationDelegate = self;
        webView.customUserAgent = "Cron";
        [self.view addSubview:webView];

        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://myUrl"]];
        [webView loadRequest:request];

Answer №1

If you want to interact with the WKWebView, one way is to utilize JavaScript functions specifically designed for them.

Once the WKWebView finishes loading (via a delegate method, for instance), you can employ the evaluateJavascript function to initiate any action on the web page or within your iOS code.

For instance:

[self.webview evaluateJavaScript:@"var bar = 2; bar * 2;" completionHandler:^(id result, NSError *error) {
    if (error == nil)
    {
        if (result != nil)
        {
            NSInteger intResult = [result integerValue]; // 4
            NSLog(@"result: %d", intResult);
        }
    }
    else
    {
        NSLog(@"evaluateJavaScript error : %@", error.localizedDescription);
    }
}];

The corresponding JavaScript function would be:

var bar = 2; bar * 2;

This allows you to define any JavaScript function from the objective-C side, or execute any function on the web side.

For example, if there's a JavaScript function on your website named:

function closeWindow()

You would call that function like this:

[self.webview evaluateJavaScript:@"closeWindow();" completionHandler:^(id result, NSError *error) {
    if (error == nil)
       // Success handling code
    } else {
        NSLog(@"evaluateJavaScript error : %@", error.localizedDescription);
    }
}];

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 best method for delivering a JavaScript string as an XML document to a user in Express.js?

I am facing a challenge where I cannot save a string buffer as a file and send it, due to my use of elastic beanstalk. However, I only have a string and I want the user to be able to download it as an XML document. router.get('/', (req, res) =&g ...

The image map library functions seamlessly with React but encounters issues when integrated with Next.js

I have been working on a client project that requires the use of an image map. I searched for a suitable library, but struggled to find one that is easy to maintain. However, I came across this particular library that seemed promising. https://github.com/ ...

Tips for successfully including special characters in a query string using asp.net and jquery

Is there a way to pass %20 in the Query string without it being interpreted as a space in the code behind? I need to pass query strings using ASP.NET and also from JavaScript. Any suggestions on how to achieve this? Thank you in advance for your help. ...

Tips for using JavaScript to consume a complex type returned by a WebMethod on the client side

I am new to Webmethods and Services and I find myself in a bit of a predicament here. The webmethod I have returns an instance of the StatusViewModel class. [WebMethod()] public static StatusViewModel GetTime1() { Debug.Write("Timer") ...

What is the reason why the 'hide menu onscroll' JavaScript function doesn't perform flawlessly on Safari web browser?

Compatibility with different browsers: works on Firefox, Chrome, and Edge. However, on Safari, the menu (navbar) behaves strangely. It appears when scrolling up but hides (floats up beyond the window) when scrolling to the top of the page without any downw ...

Steps to generate an excel document from an HTML table and store it in the project folder

I have created an HTML table with loaded data and now I am looking to convert it into an Excel file and save it in the project directory. Below is the HTML Table structure: <table class='tblNemoList' border='1' cellpadding='3 ...

Ensuring the validity of an HTML form by including onClick functionalities for additional form elements

I am working on a form that I put together using various pieces of code that I found online. My knowledge of HTML and JavaScript is very basic. The form includes a button that, when clicked, will add another set of the same form fields. Initially, I added ...

dividing JavaScript files in the three.js game development platform

After spending two years teaching myself unity/c#, I believe I have the coding skills to transition from an engine to a framework for better control over the environment. As I started working on first person environment features, I wanted to organize my co ...

How can I make the arrows work on a secondary slider with EasySlider1.7?

I finally managed to get 2 sliders working on my page after reading through several other tutorials. However, I am facing an issue with the Prev & Next arrows on the second slider as they don't seem to work properly. I inherited this page from someon ...

Creating a Custom Rule for Checkbox Validation using jQuery

Can the jQuery Validation plugin be used to validate custom values on checkboxes, rather than just True or False? For instance: <input id="test" type="checkbox" name="test" value="something"> I am struggling to find a method that can check if &apo ...

JQuery's document.ready function triggers prematurely on dynamically loaded HTML content

When loading dynamic content, I use the following method: $('#my-div').load('my.html'); The code inside my.html looks like this: <html> <head> </head> <body> <script> $(fu ...

Sending ASP.NET Components to JavaScript Functions

I've set up a text box and label in the following way: <asp:TextBox ID="MyTextBox" runat="server"/> <asp:Label ID="MyLabel" runat="server"/> Additionally, I've created a JavaScript function like this: function checkLength(myTex ...

Button missing post ajax loading

I've encountered a problem with my code that populates a table and contains buttons, which trigger an AJAX load. The content is loaded into a DIV with the ID 'DIV1', but when I try to access the buttons in that DIV1 by clicking on them, they ...

Creating an Organizational chart with the use of JavaScript

From the server, I receive JSON data. In my HTML file, I am looking to showcase an organization chart in the following format: CEO | | #Manager #Manager Utili ...

Ways to determine the position of elements when they are centered using `margin:auto`

Is there a more efficient way to determine the position of an element that is centered using CSS margin:auto? Take a look at this fiddle: https://jsfiddle.net/vaxobasilidze/jhyfgusn/1/ If you click on the element with the red border, it should alert you ...

Ensuring the accuracy of web services through validation and rules

In my experience with various web service applications, a common scenario has emerged: Initially, a Domain Model is created (using C#). This model serves as the core of the application, housing business logic and validation rules to determine entity vali ...

What method can be used to update password validation when using a different input in AngularJS?

I am working with 3 input fields like this: <div class="form-group"> <label for="username">Username</label> <input type="text" ng-model="formModel.username" class="form-control" ...

How come when I click on the edit button, the selected data's model doesn't appear in the dropdown menu as I would like it to?

this is the function in my controller public function getModel($make_id = null) { $make_id = request()->make_id; $carsmodel = CarModel::where('make_id', $make_id)->orderBy('model', 'ASC')->get(); return re ...

Guide on switching the theme color in c# aspnet core using a toggle button within a partialview

Description I am looking to change the color scheme of my Bootstrap 5.3 theme by clicking a button within a partial view. The toggle button is customized to meet my specific requirements, and the chosen value is stored in a cookie for future reference. ...

Implementing the disabled attribute in input text fields with Vue.js

There are 2 URLs that I am working with: /register /register?sponsor=4 The first route, /register, provides a clean input field where users can type freely. The second route, on the other hand, pre-fills the input with a value of 4 and disables it, ...