javascript - 我正在尝试在 URL 上使用 JSContext evaluateScript 运行 javascript
问题描述
我正在尝试evaluateScript
在 URL 上使用。在文档中它显示:
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 )
错误说:
无法使用“(字符串,URL?)”类型的参数列表调用“evaluateScript”
解决方案
你忘记了withSourceURL:
参数标签。
self.jsContext.evaluateScript(jsSourceContents, withSourceURL: newURL)
您还需要一个非可选的 URL。因此,如果您知道它不会失败,要么强制解包,要么newURL
在尝试使用它之前安全地解包。
推荐阅读
- c# - 如何使物体停在特定位置
- sql - 使用 sql azure 连接 ODBC 进度
- html - 使用字体的css中的Cutom字体
- iso8583 - 无法使用 JPOS 升级 ISO 8583 F137
- typescript - Typescript 如何推断组合类型
- android - 地理编码器不会在奥利奥上运行
- sql - 获取上个月的数字,包括年份
- xamarin.forms - 如何在 Xamarin Forms(XAML) 上添加 android:id 等 android 属性?
- typescript - 如何用简单的英文阅读`地图:(f: (a: A) => B) => (ma: M ) => M `
- c - C中的可变维数组