Skip to main content

[Swift] Using javascript alert, confirm, prompt dialog in WKWebview

Hello, today, i will explain how to webView setting for using javascript in ios webview

looking at many previous postings, UIWebView was used by many developers


but now, since the advent of WKWebView, WKWebView is most used for webview in ios swift


UIWebView has many source ,so it is may think convenient to develope


but WKWebView's speed for rendering is more higher than UIWebView, twice


and CPU utilization is more effective 


In many cases, WKWebView is more effective


If you load webview only basic way without any other setting, cannot use javascript


therefore, we need to some settings


let's setting together

import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {


Set as above


The imported class roles are as follows


// WKUIDelegate : Catching event in JavaScripts, plugin, content and give web's basic UI


// WKNavigationDelegate : Protocol, Catching trigger event in start loading, finsh error and user can define trigger event method


FYI, im not explain how to use webview, only explain how to set up webview that can use javascript in wkwebview



If you cannot use webview, recommend read other posting that inform how to use webview





In your wkwebview instace, code as follow


	let myUrl = URL(string: url)

        let myRequest = URLRequest(url: myUrl!)

        webView.load(myRequest)

        webView.uiDelegate = self

        webView.navigationDelegate = self





and add the following function


  func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
            let alertController = UIAlertController(title: "", message: message, preferredStyle: .alert)
            
            
            alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: {(action) in
                completionHandler()
            }))
            
            self.present(alertController, animated: true, completion: nil)
        }
        
    
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
            let alertController = UIAlertController(title: "", message: message, preferredStyle: .alert)
            
            
            alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
                completionHandler(true)
            }))
        
            
            alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in
                completionHandler(false)
            }))
            
            self.present(alertController, animated: true, completion: nil)
        }
    
    
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
            let alertController = UIAlertController(title: "", message: prompt, preferredStyle: .alert)
            
            alertController.addTextField { (textField) in
                textField.text = defaultText
            }
            
            
            alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
                if let text = alertController.textFields?.first?.text {
                    completionHandler(text)
                } else {
                    completionHandler(defaultText)
                }
            }))

            
            alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in
                completionHandler(nil)
            }))

            self.present(alertController, animated: true, completion: nil)
        }
    


the code is very long, but it is simple because the three functions are similar




Through the above functions, we can use alert, confirm and prompt in webView


Look closely function's parameter, The first is written 'runJavaScriptAlertPanelWithMessage'


second is 'runJavaScriptConfirmPanelWithMessage' and final is 'runJavaScriptTextInputPanelWithPromt'


the first is setting for using alert dialog and second is confirm dialog and final is prompt dialog



Through these function, we can user javascript's 'alert', 'confirm' and 'prompt'


Try it, you can see it succeed

Comments

Popular posts from this blog

[AWS EC2] How to use jconsole and visualVM [1] (remote connect Linux server)

Today, let's look at how to use jconsole and visualVm to monitor jvm memory on a Linux server. recently, i met the java memory error so i studied java memory structure and i found jconsole and visualVM which are tools that possible to monitor java memory utilization, available and capacity jconsole and visualVm provide GUI-style memory informations so if i could access remotely, it would be useful tool  now let's start  First of all, i'll tell you about my server and local environmental    server OS : Amazon linux2 WAS : tomcat7 java8   LOCAL window, java   The way of setting to connect jconsole and visualVM are same, so i explain without distinction   [Download JMXRmote.jar in your Server ]   I'll download jmx remote.jar to my local and move it to my linux server 먼저, 로컬에서 톰캣 다운로드 페이지에 가서 자신의 버전에 맞는 jmx remote.jar 파일을 다운받아주세요.  first of all, Download jmx remote.jar that matches your tomcat version from the site below  tomcat.apache.org/d...

[Swift] WKWebView, use navigator.userAgent for distinguish web and webView in ios

  Hello,  I will tell you how to distinguish whether i access mobile web or webview If you are using a webview, you will want to know the route you accessed. In general, WebView such as Hybrid App is slower than Native App, and developer sometimes use them to give animation effect such as progress bar There are many other cases Like this, Developer distributing hybridApp need to distinguish mobile web and webview for implement function only operates in webview In Javascript, we know that 'navigator.userAgent;' code informs where you accessed  If you are access in Mobile Android Web, the alert(navigator.userAgent) value executed by web server Javascript is "Mozilla/5.0 (Linux; Android 8.0.0; SM-G930K Build/R16NW; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3770.101 Mobile Safari/537.36" But unfortunately, The same goes for Android WebView. So we can't distinguish between web and webview by using only userAgent value Let's see what...

How to disable zoom in mobile web and webview(Disable zoom in IOS and Andorid)

Hello Using zoom in mobile application is important function for user It allows users to zoom in on small text to see it in detail, and zoom in on image 하지만 줌 속성이 오히려 화면의 레이아웃을 방해할 수도 있습니다.  However, the zoom function may interfere with the layout of the screen 예를 들어 html의 input 속성처럼 텍스트를 입력받는 태그에 포커스를 주면 자동으로 확대 되는 경우가 있습니다.  For example, when an input tag in html gets focus, the screen is automatically enlarged like below, At this time, the screen does not zoom out automatically even if you focus on other component or area so we have the hassle of having to zoom out ourselves  To get rid of this inconvenience , we can disable zooming in and out currently, many application also disable zooming in and out If you completely want to disable zoom in your application, you need to disable three cases the first case, when you use your finger to zoom on the screen(pinch zoom) the second, when input tag gets a focus the final, when using double tap let's disable each case - How t...