gpt4 book ai didi

ios - Swift WKWebView 与 Javascript 交互

转载 作者:搜寻专家 更新时间:2023-11-01 07:22:29 24 4
gpt4 key购买 nike

我一直无法在 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 = '...'

关于ios - Swift WKWebView 与 Javascript 交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38075950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com