首页 > 解决方案 > 我正在尝试在 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”

标签: javascriptswift

解决方案


你忘记了withSourceURL:参数标签。

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

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


推荐阅读