2017-01-25 41 views
1

我仍然在學習Swift所以請裸露在我身邊。 :)注入JavaScript到UIWebView

我想注入本地JS文件到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. 
} 
} 

謝謝你的任何及所有的幫助!

回答

0

你幾乎接近。你跳過重要的一條線在

webView.stringByEvaluatingJavaScript(from: jsPath!) 

jspath加載JS當你被錯誤注射JS路徑,而不是JS本身。因此,加載JS文件的內容:

var js = try? String(contentsOfFile: jsPath, encoding: String.Encoding.utf8) 

然後,將移交給js的WebView如常。

webView.stringByEvaluatingJavaScript(from: js!)