繁体   English   中英

Swift WKWebView和Javascript交互

[英]Swift WKWebView and Javascript Interaction

我一直无法在Swift中获得WKWebView来触发已加载网页中的一些JavaScript。 我只是想在用户向左滑动,向右滑动或单击按钮时使用javascript更改网站上的背景颜色。 任何帮助是极大的赞赏。

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

}

您拼写了Javascript的函数名称。 应该是getElementById而不是getElementByID

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM