NEW: Join my free 100 Days of SwiftUI challenge today! >>

How to run JavaScript on a UIWebView with stringByEvaluatingJavaScript(from:)

Swift version: 5.1

Paul Hudson    @twostraws   

If you’re still using the deprecated UIWebView, you can run custom JavaScript on it using the method stringByEvaluatingJavaScript(from:). The method returns an optional string, which means if the code returns a value you'll get it back otherwise you'll get back nil.

Here's an example that pulls out the current page's title:

let pageTitle = yourUIWebView.stringByEvaluatingJavaScript(from: "document.title")

Note: if you're using a WKWebView you can use its title property directly to get the same thing.

LEARN SWIFTUI FOR FREE I have a massive, free SwiftUI video collection on YouTube teaching you how to build complete apps with SwiftUI – check it out!

Available from iOS 2.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.5/5