[英]Execute javaScript in UIWebView in Swift
I am trying to execute the Amazon Mobile Add in my iOS application using Swift 3.0. 我正在尝试使用Swift 3.0在我的iOS应用程序中执行Amazon Mobile Add。 The file loads successfully.
文件加载成功。 I can run the google URL (code commented below) in the webView.
我可以在webView中运行google URL(下面注释的代码)。 I don't understand how to execute the javaScript.
我不明白如何执行javaScript。 I have been reading tutorials, but nothing seems to run the script as-is natively in the webView.
我一直在阅读教程,但似乎没有任何内容可以在webView中原生运行脚本。 I tried the webView.stringByEvaluatingJavaScript and the context.evaluateScript, but all I get is "Amazon Ad" and not the script output in the webView.
我尝试了webView.stringByEvaluatingJavaScript和context.evaluateScript,但我得到的只是“ Amazon Ad”,而不是webView中的脚本输出。
My question is, how do I run javaScript in the simplest way in a webView - or any other view for that matter. 我的问题是,如何在webView或任何其他视图中以最简单的方式运行javaScript。 xxxxx are "redacted" user keys.
xxxxx是“已编辑的”用户密钥。
<!DOCTYPE html>
<html>
<body>
<h1>Amazon Ad</h1>
<script type="text/javascript">
amzn_assoc_placement = "xxxxxx";
amzn_assoc_search_bar = "true";
amzn_assoc_tracking_id = "xxxxxx";
amzn_assoc_search_bar_position = "bottom";
amzn_assoc_ad_mode = "search";
amzn_assoc_ad_type = "smart";
amzn_assoc_marketplace = "amazon";
amzn_assoc_region = "US";
amzn_assoc_title = "Star Wars Black Series 6\"";
amzn_assoc_default_search_phrase = "Star Wars Black Series 6 Inch";
amzn_assoc_default_category = "All";
amzn_assoc_linkid = "xxxxxxx";
</script>
<script src="//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US"></script>
</body>
</html>
Here is the UIViewController with UIWebView. 这是带有UIWebView的UIViewController。 I tried both of the following,
我尝试了以下两种方法
webView.stringByEvaluatingJavaScript(from: common),
webView.loadHTMLString(common, baseURL: Bundle.main.bundleURL)
Code 码
import UIKit
import JavaScriptCore
class AmazonFullAdViewController: UIViewController, UIWebViewDelegate {
@IBOutlet weak var webView: UIWebView!
var url = URL(string: "https://google.com")
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
// 1
guard let commonJSPath = Bundle.main.path(forResource: "common", ofType: "js") else {
//commonJSPath = Bundle.main.path(forResource: "Series", ofType: "txt") else {
print("Unable to read resource files.")
return
}
// 2
do {
let common = try String(contentsOfFile: commonJSPath, encoding: String.Encoding.utf8)
_ = context?.evaluateScript(common)
// webView.stringByEvaluatingJavaScript(from: common)
webView.loadHTMLString(common, baseURL: Bundle.main.bundleURL)
} catch (let error) {
print("Error while processing script file: \(error)")
}
//load initial URL
// let req = URLRequest(url : url!)
// webView.scalesPageToFit = true
// webView.contentMode = .scaleAspectFit
// webView.loadRequest(req)
}
}
我认为您需要告诉webview
它需要加载一个html值,因为您的文件是带有javascript的html。
self.webview.loadHTMLString(yourfile)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.