2023-03-15

2023-03-14  本文已影响0人  lionnner
func testWebViewLoadJS(){
    let webView = UIWebView(frame: CGRect.zero) // import UIKit
//    let webView = WKWebView(frame: .zero) //import WebKit
    
    let path = Bundle.main.path(forResource: "your_javascript_file", ofType: "js")
    let request = URLRequest(url: URL(fileURLWithPath: path!))
    webView.loadRequest(request)

//    let request1 = URLRequest(url: URL(string: "https://xxxx.js"))
//    webView.loadRequest(request1)

    let result = webView.stringByEvaluatingJavaScript(from: "your_function_name()")
    
}
func testJSContext(){
    
    // local js
    let context = JSContext()
    let filePath = Bundle.main.path(forResource: "your_javascript_file", ofType: "js")
    let jsString = try? String(contentsOfFile: filePath!)
    context?.evaluateScript(jsString)
    
    let function = context?.objectForKeyedSubscript("your_function_name")
    let result = function?.call(withArguments: [])
    
    
    //remote
    let url = URL(string: "https://example.com/myscript.js")!

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let data = data else {
            print("Error downloading script: \(error?.localizedDescription ?? "Unknown error")")
            return
        }
        
        // 创建 JSContext 对象
        let context = JSContext()
        
        // 执行 JavaScript 代码
        context?.evaluateScript(String(data: data, encoding: .utf8))
        
        // 调用 JavaScript 函数
        let function = context?.objectForKeyedSubscript("your_function_name")
        let result = function?.call(withArguments: [])
        
        print(result?.toString() as Any)
    }

    task.resume()
}
上一篇下一篇

猜你喜欢

热点阅读