简体   繁体   English

iOS Swift 5:如何在 WKWebView 中执行 js 文件?

[英]iOS Swift 5: How to execute a js file in a WKWebView?

How can i execute script.js in WKWebView ?如何在WKWebView 中执行script.js I know about webView.evaluateJavaScript but i can't figure out how to evaluate my script.js file, i already tried some solutions i found on stackoverflow by other users but nothing works can anybody help me with this?我知道webView.evaluateJavaScript但我不知道如何评估我的 script.js 文件,我已经尝试了其他用户在 stackoverflow 上找到的一些解决方案,但没有任何效果有人可以帮助我吗? i'm losing my mind:(我快疯了:(

This is what i tried:这是我试过的:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
                       webView.evaluateJavaScript("script.js", completionHandler: nil)
               }

If you are just trying to run some javascript but you don't actually want to connect it to an HTML document then you should be using JavaScriptCore rather than WKWebview.如果您只是想运行一些 javascript 但实际上并不想将其连接到 HTML 文档,那么您应该使用JavaScriptCore而不是 WKWebview。

import JavaScriptCore

let context = JSContext()

guard let path = Bundle.main.path(forResource: "script", ofType: "js"),
  let script = try? String(contentsOfFile: path, encoding: .utf8) else {
    fatalError("cannot load script")
}

let jsResult = context?.evaluateScript(script)
print(jsResult)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM