WKWebView - Javascript确认和警报不起作用 [英] WKWebView - Javascript Confirm and Alert not working

查看:173
本文介绍了WKWebView - Javascript确认和警报不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用WKWebView打开example.com,在那里我有一个测试链接,应该打开一个JS警报,但我不能让它显示在设备上,它只有在我工作时才有效从浏览器查看该网站。

I am using WKWebView to open up example.com, and on there I have a test link which is supposed to open up a JS alert, but I can't get it to display on the device, it only works if I view the site from browser.

我正在使用WKUIDelegate,并将这段代码添加到ViewController.swift文件中:

I am using WKUIDelegate, and added this piece of code to the ViewController.swift file:

func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (() -> Void)) {

    NSLog("Hello")
}

我在XCode控制台中看不到任何内容当我点击产生JS警报的链接时。

I don't see anything in the XCode console when I click the link that spawns the JS alert.

我缺少什么?

推荐答案

您还需要在WKWebView上设置uiDelegate。

You also need to set the uiDelegate on the WKWebView.

import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {

    var wkWebView: WKWebView!

    public override func viewDidLoad() {
        super.viewDidLoad()

        wkWebView = WKWebView(frame: view.bounds, configuration: WKWebViewConfiguration())
        wkWebView.uiDelegate = self
        wkWebView.navigationDelegate = self
        view.addSubview(wkWebView!)
        let url = URL(string: "https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert")!
        wkWebView.load(URLRequest(url: url))
    }

    func webView(_ webView: WKWebView,
                 runJavaScriptAlertPanelWithMessage message: String,
                 initiatedByFrame frame: WKFrameInfo,
                 completionHandler: @escaping () -> Void) {

        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        let title = NSLocalizedString("OK", comment: "OK Button")
        let ok = UIAlertAction(title: title, style: .default) { (action: UIAlertAction) -> Void in
            alert.dismiss(animated: true, completion: nil)
        }
        alert.addAction(ok)
        present(alert, animated: true)
        completionHandler()
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        wkWebView.evaluateJavaScript("alert('Hello from evaluateJavascript()')", completionHandler: nil)
    }
}

confirm() prompt()查看其他委托方法。

For confirm() and prompt() see the other delegate methods.

这篇关于WKWebView - Javascript确认和警报不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆