在Swift的UIWebView中执行javaScript

在Swift的UIWebView中执行javaScript,javascript,ios,swift3,uiwebview,Javascript,Ios,Swift3,Uiwebview,我正在尝试使用Swift 3.0在我的iOS应用程序中执行Amazon Mobile插件。文件加载成功。我可以在webView中运行google URL(下面注释的代码)。我不明白如何执行javaScript。我一直在阅读教程,但似乎没有任何东西像webView中本机那样运行脚本。我尝试了webView.stringByEvaluatingJavaScript和context.evaluateScript,但我得到的只是“Amazon广告”,而不是webView中的脚本输出 我的问题是,如何在w

我正在尝试使用Swift 3.0在我的iOS应用程序中执行Amazon Mobile插件。文件加载成功。我可以在webView中运行google URL(下面注释的代码)。我不明白如何执行javaScript。我一直在阅读教程,但似乎没有任何东西像webView中本机那样运行脚本。我尝试了webView.stringByEvaluatingJavaScript和context.evaluateScript,但我得到的只是“Amazon广告”,而不是webView中的脚本输出

我的问题是,如何在webView或任何其他视图中以最简单的方式运行javaScript。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>
代码


我认为您需要告诉
webview
它需要加载一个html值,因为您的文件是一个包含javascript的html文件


self.webview.loadHTMLString(yourfile)

我将javascript代码封装在标记中。如果我在浏览器中运行html,它会连接并运行良好。当我使用webView.loadHTMLString(common,baseURL:Bundle.main.bundleURL)时,web视图中不会呈现任何内容。该代码调用委托-func webViewDidFinishLoad
webView.stringByEvaluatingJavaScript(from: common), 
webView.loadHTMLString(common, baseURL: Bundle.main.bundleURL)
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)
}
}