【发布时间】:2017-08-16 11:18:52
【问题描述】:
我在我的应用程序中展示了一个 WebView,但是,我想在我展示的网站上进行一些修改。例如,如果我加载 google.com,我可能想要更改“google 搜索”按钮的文本。我该怎么做?
提出的类似问题都在 Objective C 中,并且似乎不起作用。 提前谢谢你。
【问题讨论】:
我在我的应用程序中展示了一个 WebView,但是,我想在我展示的网站上进行一些修改。例如,如果我加载 google.com,我可能想要更改“google 搜索”按钮的文本。我该怎么做?
提出的类似问题都在 Objective C 中,并且似乎不起作用。 提前谢谢你。
【问题讨论】:
我认为这会对您有所帮助。在 Swift3 中
@IBOutlet weak var webView: UIWebView!
var firstLoad = true
override func viewDidLoad() {
super.viewDidLoad()
self.webView.delegate = self
self.webView.loadRequest(URLRequest(url: URL(string: "https://www.google.com.pk/")!))
// Do any additional setup after loading the view, typically from a nib.
}
func webViewDidFinishLoad(_ webView: UIWebView) {
let evaluate: String = "document.getElementById('main-title').value='\("New title")';"
webView.stringByEvaluatingJavaScript(from: evaluate)
//or
if firstLoad {
firstLoad = false
let html: String? = webView.stringByEvaluatingJavaScript(from: "document.documentElement.outerHTML")
//Edit html here, by parsing or similar.
webView.loadHTMLString(html!, baseURL: Bundle.main.resourceURL)
//print HTML for testing
print("HTML \(html!)")
}
}
【讨论】:
UIWebView 的stringByEvalutingJavascript() 会给你想要的控制。您只需编写 javascript 即可更改您定位的内容。