kampbell411 kampbell411 - 5 months ago 183
Swift Question

Swift WKWebView and Javascript Interaction

I've been having trouble getting a WKWebView in Swift to trigger some javascript in the loaded web page. Im just trying to use javascript to change a background color on the website if the user swipes left, swipes right, or clicks a button. Any help is greatly 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)
}

}

Answer

You misspelled the Javascript's function name. It should be getElementById instead of getElementByID:

document.getElementById('hplogo').style.backgroundColor = '...'