javascript - 我正在尝试在 URL 上使用 JSContext evaluateScript 运行 javascript

标签 javascript swift

我正在尝试在 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 )

错误说:

Cannot invoke 'evaluateScript' with an argument list of type '(String, URL?)'

最佳答案

您忘记了 withSourceURL: 参数标签。

self.jsContext.evaluateScript(jsSourceContents, withSourceURL: newURL)

您还需要一个非可选的 URL。因此,如果您知道它不会失败,或者在尝试使用它之前安全地解包它,要么强制解包 newURL

关于javascript - 我正在尝试在 URL 上使用 JSContext evaluateScript 运行 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55554607/

相关文章:

swift - Dictionary 在 Swift 中如何使用 Equatable 协议(protocol)?

ios - UITableView 上的某些单元格不会自动调整大小

ios - 如何从 Swift3 iOS 中的对象数组中查找唯一值

javascript - 将 <Script> 标签附加到正文?

javascript - 是否有机会通过 css 将 div 类插入 javascript

javascript - 将div标签变成输入框

ios - 转换为 CGImage 时 UIImage 大小加倍?

swift - 如何在 UITabBarController 的 TabBar 项之间插入分隔符

javascript - 获取上周六的日期和下周五的日期

javascript - 我如何解决集中听众的个人 promise ?