简体   繁体   中英

Calling Javascript function from Swift returns undefined

I have JS file of "jsrsasign". It creates public and private key pairs. I would like to get that pair from Swift. There is a function called KEYUTIL.generateKeypair("RSA",2048); . I would like to call this function from swift. However, result returns me "undefined".

Below is the javascript functions:

var myPublicKey = function myKeyFunction() {
  return KEYUTIL.generateKeypair("RSA", 2048);
}
var key = KEYUTIL.generateKeypair("RSA", 2048);
pm.environment.set("private_key_client", KEYUTIL.getPEM(key.prvKeyObj, "PKCS8PRV").split("\r\n").join("\n"));
pm.environment.set("public_key_client", KEYUTIL.getPEM(key.pubKeyObj).split("\r\n").join("\n"));

Swift codes:

if let jsSourcePath = Bundle.main.url(forResource: "rsakeygenerator", withExtension: "js") {
            do {
                let jsHandler = JSCommunicationHandler()
                jsHandler.loadSourceFile(atUrl: jsSourcePath)
                let result = jsHandler.evaluateJavaScript("myPublicKey")
            }
            catch {
                print(error.localizedDescription)
            }
        }

My Helper Class:

class JSCommunicationHandler {
private let context = JSContext()

init() {
    context?.exceptionHandler = {context, exception in
        if let exception = exception {
            print(exception.toString()!)
        }
    }
}

func callFunction<T>(functionName:String, withData dataObject:Codable, type:T.Type) -> JSValue? where T:Codable {
    var dataString = ""
    if let string = getString(fromObject: dataObject, type:type) {
        dataString = string
    }
    let functionString = functionName + "(\(dataString))"
    let result = context?.evaluateScript(functionString)
    return result
}

func loadSourceFile(atUrl url:URL) {
    guard let stringFromUrl = try? String(contentsOf: url) else {return}
    context?.evaluateScript(stringFromUrl)
}

func evaluateJavaScript(_ jsString:String) -> JSValue? {
    context?.evaluateScript(jsString)
}

func setObject(object:Any, withName:String) {
    context?.setObject(object, forKeyedSubscript: withName as NSCopying & NSObjectProtocol)
}
}

extension JSCommunicationHandler {
    private func getString<T>(fromObject jsonObject:Codable, type:T.Type) -> String? where T:Codable {
        let encoder = JSONEncoder()
        guard let dataObject = jsonObject as? T,
            let data = try? encoder.encode(dataObject),
            let string = String(data:data, encoding:.utf8) else  {
                return nil
        }
        return string
    }
}

I found that I need to set navigator and window at the end of the javascript file.

navigator={name:"Postman",version:"1.0"};
window={};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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