我正在尝试在URL上使用evaluateScript
。在文档中显示:
func evaluateScript(_ script: String!, withSourceURL sourceURL: URL!) -> JSValue!
func initializeJS() {
self.jsContext = JSContext()
// Specify the path to the jssource.js file.
if let jsSourcePath = Bundle.main.path(forResource: "Rejistration", ofType: "js") {
do {
// Load its contents to a String variable.
let jsSourceContents = try String(contentsOfFile: jsSourcePath)
// Add the Javascript code that currently exists in the jsSourceContents to the Javascript Runtime through the jsContext object.
let newURL = URL(string: "https://google.com/")
self.jsContext.evaluateScript(jsSourceContents, newURL )
if let variableHelloWorld = self.jsContext.objectForKeyedSubscript("helloWorld") {
print(variableHelloWorld.toString())
}
}
catch {
print(error.localizedDescription)
}
}
}
在线错误:
self.jsContext.evaluateScript(jsSourceContents, newURL )
错误说:
无法使用类型为'(String,URL?)'的参数列表调用'evaluateScript'
答案 0 :(得分:1)
您忘记了withSourceURL:
参数标签。
self.jsContext.evaluateScript(jsSourceContents, withSourceURL: newURL)
您还需要一个非可选的URL。因此,如果您知道newURL
不会失败,则可以将其强行打开,或者在尝试使用它之前先安全地对其进行打开。