无法在Swift中将JS加载到WebView中

时间:2014-11-11 13:46:58

标签: javascript xcode macos swift webview

我试图将JavaScript注入我正在加载WebView的网页中。我得到了这个:

override func webView(sender: WebView!, didClearWindowObject windowObject: WebScriptObject!, forFrame frame: WebFrame!) {
    if (webView.mainFrameDocument != nil) { // && frame.DOMDocument == webView.mainFrameDocument) {
        let document:DOMDocument = webView.mainFrameDocument
        let hangoutsMode: String? = Preferences.getString("hangoutsMode")
        let windowScriptObject = webView.windowScriptObject;
        windowScriptObject.setValue(self, forKey: "gInbox")
        windowScriptObject.evaluateWebScript("console = { log: function(msg) { gInbox.consoleLog(msg); } }")

        let path = NSBundle.mainBundle().pathForResource("gInboxTweaks", ofType: "js", inDirectory: "Assets")
        let jsString = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)
        let script = document.createElement("script")
        let jsText = document.createTextNode(jsString)
        let bodyEl = document.getElementsByName("body").item(0)

        script.setAttribute("type", value: "text/javascript")
        script.appendChild(jsText)
        bodyEl?.appendChild(script)

        windowScriptObject.evaluateWebScript(String(format: "console.log('test'); hangoutsMode(%@)", hangoutsMode!))
    }
}

哪个在目标C中起作用,但不再在Swift中起作用。我不确定它到底出了什么问题,但它无法找到bodyEl并且它仍然是零。我尝试修改(或完全删除)外部的if,但没有。

0 个答案:

没有答案