我正在尝试将本地 JS 文件注入(inject)到 UIWebView
中。我已将其设置为加载该网站的桌面版本,但它似乎不起作用。我在 Swift 3 中找不到任何东西来做到这一点,并尝试将其拼凑在一起,但似乎我遇到了困难。
这是我到目前为止所得到的:
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
UserDefaults.standard.register(defaults: ["UserAgent": "custom value"])
webView.loadRequest(URLRequest(url: URL(string: "https://www.myfitnesspal.com/account/login")!))
func webViewDidFinishLoad(webView: UIWebView) {
let jsPath = Bundle.main.path(forResource: "mfpketo.user", ofType: "js")
webView.stringByEvaluatingJavaScript(from: jsPath!)
print("test")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
最佳答案
你已经接近了。您跳过了重要的一行从 jspath
加载 JS
in
webView.stringByEvaluatingJavaScript(from: jsPath!)
你错误地注入(inject)了js路径而不是js本身。因此,加载js文件的内容:
var js = try? String(contentsOfFile: jsPath, encoding: String.Encoding.utf8)
然后,照常将js
移交给webview。
webView.stringByEvaluatingJavaScript(from: js!)
关于javascript - 将 JavaScript 注入(inject) UIWebView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41846286/