当在WKWebView上通过“evaluateJavaScript”调用函数时,会出现JavaScript异常,WKWebView有一个本地的.js文件

时间:2022-09-01 16:00:38

We have a sample HTML page, which just links the .js file:

我们有一个示例HTML页面,它只链接.js文件:

sample.html:

sample.html:

<html>
    <head>
        <script src="test.js"></script>
    </head>
    <body></body>
</html>

The .js file is literally just:

js文件字面上就是:

test.js

. js

function myFunction() {
    return "hello";
}

So All I want is to evaluate that Javascript function (for now). In the Swift file:

现在我只想计算这个Javascript函数。斯威夫特的文件:

let webView = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
let path = Bundle.main.url(forResource: "sample", withExtension: "html")!
let text = try! String(contentsOf: path, encoding: String.Encoding.utf8)

webView.loadHTMLString(text, baseURL: nil)
webView.evaluateJavaScript("myFunction()") { (any, error) in
    dump(error)
}

Two which we get the error:

第二个错误是

Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=ReferenceError: Can't find variable: myFunction, WKJavaScriptExceptionSourceURL=about:blank, NSLocalizedDescription=A JavaScript exception occurred, WKJavaScriptExceptionColumnNumber=11}

错误域=WKErrorDomain Code=4 "出现了一个JavaScript异常" UserInfo={wkjavastexceptionlinenumber =1, wkjavastexceptionmessage =ReferenceError:找不到变量:myFunction, wkjavastexceptionsourceurl =about:blank, NSLocalizedDescription=发生了一个JavaScript异常

Am I approaching this totally wrong?

我是不是完全错了?

1 个解决方案

#1


6  

You're not that far.

你不是那么远。

First, you can either modify your code by setting the baseURL:

首先,您可以通过设置baseURL来修改代码:

webView.loadHTMLString(text, baseURL: path)

or use an URLRequest instead (better in my opinion).

或者使用URLRequest(在我看来更好)。

if let path = Bundle.main.url(forResource: "sample", withExtension: "html"){  
    let myURLRequest:URLRequest = URLRequest(url: path)
    webView.load(myURLRequest)
}

The second thing is you have to wait for the content to be loaded. So you first need to set a delegate for your webview (Make sure you add this line before before loading the html).

第二件事是您必须等待内容被加载。因此,首先需要为webview设置一个委托(确保在加载html之前添加这一行)。

webView.navigationDelegate = self

Then, add an extension to your class for the delegate ( My class is named "ViewController" here, but change it to the name of your class ) to call evaluateJavascript when the page is loaded.

然后,为这个委托添加一个扩展到您的类(我的类在这里被命名为“ViewController”,但是将它更改为类的名称)在加载页面时调用evaluateJavascript。

extension ViewController: WKNavigationDelegate {

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("Finished navigating to url \(webView.url)")

        webView.evaluateJavaScript("myFunction()") { (any, error) in
            dump(error)
            print(any)
        }

    }
}

#1


6  

You're not that far.

你不是那么远。

First, you can either modify your code by setting the baseURL:

首先,您可以通过设置baseURL来修改代码:

webView.loadHTMLString(text, baseURL: path)

or use an URLRequest instead (better in my opinion).

或者使用URLRequest(在我看来更好)。

if let path = Bundle.main.url(forResource: "sample", withExtension: "html"){  
    let myURLRequest:URLRequest = URLRequest(url: path)
    webView.load(myURLRequest)
}

The second thing is you have to wait for the content to be loaded. So you first need to set a delegate for your webview (Make sure you add this line before before loading the html).

第二件事是您必须等待内容被加载。因此,首先需要为webview设置一个委托(确保在加载html之前添加这一行)。

webView.navigationDelegate = self

Then, add an extension to your class for the delegate ( My class is named "ViewController" here, but change it to the name of your class ) to call evaluateJavascript when the page is loaded.

然后,为这个委托添加一个扩展到您的类(我的类在这里被命名为“ViewController”,但是将它更改为类的名称)在加载页面时调用evaluateJavascript。

extension ViewController: WKNavigationDelegate {

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("Finished navigating to url \(webView.url)")

        webView.evaluateJavaScript("myFunction()") { (any, error) in
            dump(error)
            print(any)
        }

    }
}