美文网首页
2023-03-15

2023-03-15

作者: lionnner | 来源:发表于2023-03-14 10:50 被阅读0次
    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()
    }
    

    相关文章

      网友评论

          本文标题:2023-03-15

          本文链接:https://www.haomeiwen.com/subject/tlohrdtx.html