Javascript Can';t在Swift中将JS加载到WebView中
我正在尝试将JavaScript注入到使用WebView加载的网页中。我做到了这一点:Javascript Can';t在Swift中将JS加载到WebView中,javascript,xcode,macos,swift,webview,Javascript,Xcode,Macos,Swift,Webview,我正在尝试将JavaScript注入到使用WebView加载的网页中。我做到了这一点: override func webView(sender: WebView!, didClearWindowObject windowObject: WebScriptObject!, forFrame frame: WebFrame!) { if (webView.mainFrameDocument != nil) { // && frame.DOMDocument == webVi
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
,但什么也没有