ios - Swift WKWebView and Javascript Interaction -
i've been having trouble getting wkwebview in swift trigger javascript in loaded web page. im trying use javascript change background color on website if user swipes left, swipes right, or clicks button. appreciated.
import uikit import webkit class myviewcontroller: uiviewcontroller, wknavigationdelegate { @iboutlet var container: uiview! var webview: wkwebview? override func viewdidload() { super.viewdidload() self.webview = wkwebview() container.addsubview(webview!) webview?.allowsbackforwardnavigationgestures = true webview?.navigationdelegate = self let leftswipe = uiswipegesturerecognizer(target: self, action: #selector(myviewcontroller.handleswipes(_:))) let rightswipe = uiswipegesturerecognizer(target: self, action: #selector(myviewcontroller.handleswipes(_:))) leftswipe.direction = .left rightswipe.direction = .right view.addgesturerecognizer(leftswipe) view.addgesturerecognizer(rightswipe) } override func viewdidappear(animated: bool) { let frame = cgrectmake(0, 0, container.bounds.width, container.bounds.height) webview!.frame = frame let url = nsurl(string: "https://www.google.com") let request = nsurlrequest(url: url!) self.webview!.loadrequest(request) } @ibaction func buttonclick(sender: anyobject) { webview?.evaluatejavascript("document.getelementbyid('hplogo').style.backgroundcolor='red';", completionhandler: nil) } func handleswipes(sender:uiswipegesturerecognizer){ if (sender.direction == .left){ webview?.evaluatejavascript("document.getelementbyid('hplogo').style.backgroundcolor='black';", completionhandler: nil) } if (sender.direction == .right){ webview?.evaluatejavascript("document.getelementbyid('hplogo').style.backgroundcolor='green';", completionhandler: nil) } } func webview(webview: wkwebview, didfinishnavigation navigation: wknavigation!) { webview?.evaluatejavascript("document.getelementbyid('hplogo').style.backgroundcolor='red';", completionhandler: nil) } }
you misspelled javascript's function name. should getelementbyid
instead of getelementbyid
:
document.getelementbyid('hplogo').style.backgroundcolor = '...'
Comments
Post a Comment