首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >WKWebView与Javascript的交互作用

WKWebView与Javascript的交互作用
EN

Stack Overflow用户
提问于 2016-06-28 12:13:22
回答 1查看 2K关注 0票数 1

我很难在Swift中获得一个WKWebView来在加载的网页中触发一些javascript。我只是尝试使用javascript改变一个背景颜色在网站上,如果用户滑动左,右,或单击一个按钮。任何帮助都是非常感谢的。

代码语言:javascript
代码运行次数:0
运行
复制
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)
}

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-28 14:52:14

你拼错了Javascript的函数名。应该是getElementById而不是getElementByID

代码语言:javascript
代码运行次数:0
运行
复制
document.getElementById('hplogo').style.backgroundColor = '...'
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38075950

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档