title: Execute javaScript in UIWebView in Swift
body: <p>I am trying to execute the Amazon Mobile Add in my iOS application using Swift 3.0.  The file loads successfully.  I can run the google URL (code commented below) in the webView.  I don't understand how to execute the  javaScript.  I have been reading tutorials, but nothing seems to run the script as-is natively in the 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.</p>
  
  <p>My question is, how do I run javaScript  in the simplest way in a webView - or any other view for that matter.  xxxxx are "redacted" user keys.</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;body&gt;
  
  &lt;h1&gt;Amazon Ad&lt;/h1&gt;
  
  &lt;script type="text/javascript"&gt;
  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";
  &lt;/script&gt;
  &lt;script src="//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US"&gt;&lt;/script&gt;
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Here is the UIViewController with UIWebView.  I tried both of the following,</p>
  
  <pre><code>webView.stringByEvaluatingJavaScript(from: common), 
  webView.loadHTMLString(common, baseURL: Bundle.main.bundleURL)
  </code></pre>
  
  <p>Code</p>
  
  <pre><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)
  }
  }
  </code></pre>