kampbell411 kampbell411 - 1 year ago 542
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() {

self.webView = WKWebView()

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


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!)


@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 Source

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

document.getElementById('hplogo').style.backgroundColor = '...'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download