• Stars
    star
    564
  • Rank 79,014 (Top 2 %)
  • Language
    Swift
  • License
    MIT License
  • Created almost 9 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Erik is an headless browser based on WebKit. An headless browser allow to run functional tests, to access and manipulate webpages using javascript.

Erik

Join the chat at https://gitter.im/phimage/Erik License Platform Language Issues CocoapodCarthage compatible

Become a Patron! Buy me a coffee

Erik is a headless browser based on WebKit and HTML parser Kanna.

An headless browser allow to run functional tests, to access and manipulate webpages using javascript.

let browser = Erik.visit(url: url) { document, error in
    // browse HTML element, click, submit form and more
}

Navigation

Go to an url

Erik.visit(url: url) { object, error in
    if let e = error {

    } else if let doc = object {
        // HTML Inspection
    }
}

How to get current url?

if let url = Erik.currentURL {..}

For multiple browsing you can create an instance of headless browser and use same functions

let browser = Erik()
browser.visitURL...

HTML Inspection

Search for nodes by CSS selector

for link in doc.querySelectorAll("a, link") {
    print(link.text)
    print(link["href"])
}

Edit first input field with name "user"

if let input = doc.querySelectorAll("input[name=\"user\"]").first {
    input["value"] = "Eric"
}

Submit a form

if let form = doc.querySelector("form[id='search']") as? Form {
    form.submit()
}

Evaluate some JavaScript

let javaScriptSource = "console.log("test");"
Erik.evaluate(javaScript:javaScriptSource) { (obj, err) -> Void in
    if let error = err {
        switch error {
            case ErikError.javaScriptError(let message):
            print(message)
            default :
            print("\(error)")
        }
    }
    else if let capturedValue = obj {
        // do something according to result
    }
}

capturedValue is the content of JavaScript variable resultErik Affect this variable in your JavaScript code.

let javaScriptSource = "console.log('test'); var resultErik = 1 + 1;"

Warning about DOM change

⚠️ All action on Dom use JavaScript and do not modify the actual Document object and its children Element.

You must use currentContent to get a refreshed Document object

Get current content

Erik.currentContent { (obj, err) -> Void in
    if let error = err {
    }
    else if let document = obj {
       // HTML Inspection
    }
}

Using Future

As an optional feature, you can use Future/Promise ( Erik use frameworks BrightFutures & Result)

Example to submit a google search

let url = NSURL(string:"https://www.google.com")!
let value = "Erik The Phantom of Opera"
// visit
var future: Future<Document, NSError> = Erik.visitFuture(url: url)
// fill input field
future = future.flatMap { document -> Future<Document, NSError> in
    if let input = document.querySelector("input[name='q']") {
        input["value"] = value
    }
    if let form = document.querySelector("form[name=\"f\"]") as? Form {
        form.submit()
    }
    return Erik.currentContentFuture()
}
// finally get final result as success or error
future.onSuccess { document in
    // parse result
}
future.onFailure { error in
    print("\(error)")
}

Limitation

On iOS 9 and macOS 10.11, you need to ensure you use https://, because iOS 9 and macOS 10.11 do not like apps sending or receiving data insecurely. If this something you want to override, click here to read about App Transport Security.

Links

Setup

Using cocoapods

CocoaPods is a centralized dependency manager for Objective-C and Swift. Go here to learn more.

  1. Add the project to your Podfile.

    use_frameworks!
    
    pod 'Erik'
    // or specific target
    target :test do
       pod 'Erik'
    end
  2. Run pod install and open the .xcworkspace file to launch Xcode.

Optional Future

Add pod 'Erik/Future' to your Podfile and run pod install.

Using carthage

Carthage is a decentralized dependency manager for Objective-C and Swift.

  1. Add the project to your Cartfile.

    github "phimage/Erik"
    

Roadmap

  • (WIP) WKWebView screenshot (webkit view privates api?)

Why Erik?

A well known headless browser is named PhantomJS and a very well known browser is Opera.

As a tribute I use Erik, firstname of the title character from Gaston Leroux's novel Le Fantôme de l'Opéra best known to English speakers as The Phantom of Opera

My name is also Erik. So egotistical to call a project using its firstname isn't it.

My only justification is that I was playing Metal Gear Solid V and the creator Hideo Kojima name appears over 100 times in the game. Coincidentally the full name of the game is Metal Gear Solid V : The Phantom Pain.

License

The MIT License. See the LICENSE file for more information.

More Repositories

1

Prephirences

Prephirences is a Swift library that provides useful protocols and convenience methods to manage application preferences, configurations and app-state. UserDefaults
Swift
573
star
2

CallbackURLKit

Implementation of x-callback-url (Inter app communication) in swift
Swift
323
star
3

CustomSegue

Custom segue for OSX Storyboards with slide and cross fade effects (NSViewControllerTransitionOptions)
Swift
124
star
4

morphi

Shapes for SwiftUI ♡☾
Swift
71
star
5

Arithmosophi

A set of protocols for Arithmetic, Statistics and Logical operations
Swift
66
star
6

ApplicationGroupKit

Share informations betweens your applications and your extensions using group identifier
Swift
38
star
7

MacModelDump

Dump apple website to get mac model identifier and image url
Swift
26
star
8

Alamofire-Prephirences

Remote preference and configuration for your application
Swift
22
star
9

XcodeProjKit

Parse project file and write it to open step format.
Swift
16
star
10

CryptoPrephirences

Add some encryption to your sensitive preferences
Swift
11
star
11

Phiole

Allow to write or read from standards stream or files for script or CLI application
Swift
8
star
12

SLF4Swift

Simple Logging Facade for Swift serves as a simple facade for logging frameworks allowing the end user to plug in the desired logging framework at deployment time
Swift
8
star
13

ValueTransformerKit

ValueTransformer toolkit for swift
Swift
8
star
14

AlertController

An NSViewController to display an alert message to the user. This class replaces the NSAlert class.
Swift
8
star
15

Notarize

Command line utility to notarize apple application
Swift
7
star
16

MomXML

Create or parse CoreData managed object model XMLs
Swift
6
star
17

RandomDistributionKit

RandomKit extension to produce random numbers using different distribution
Swift
5
star
18

PhiLipsStack

(do not use) PhiLipsStack aims to create a CoreData stack from model to context and provide some functions on your managed object which use by default the default stack context but not only
Swift
5
star
19

plistconvert

Convert plist from different format: xml, json, binary, openStep
Shell
4
star
20

Alamofire-YamlSwift

Add Yaml response serializer to Alamofire
Swift
4
star
21

action-swift-cli-build

Build swift cli tool on macOS or ubuntu
3
star
22

FileZipKit

FileKit and ZipFoundation utility methods
Swift
3
star
23

NotarizeProcess

Utility object to launch `xcrun altool` to get notarization information
Swift
3
star
24

punic

Add third party project sources into your workspace instead of Carthage binary
Swift
3
star
25

swift-cli-template

Shell
2
star
26

Appify

Generate simple macOS `.app` from Swift Package `.executable`.
Swift
2
star
27

sebulba

Swift command line to remove de-integrate reference to cocoa pods
Swift
2
star
28

tanit

Command line application to manage Carthage binaries
Swift
1
star
29

NotarizationInfo

Decode info from apple notarization process
Swift
1
star
30

NotarizationAuditLog

Decode JSON audit log from notarization process
Swift
1
star
31

phimage

1
star
32

xprojup

Swift
1
star
33

cd2sql

Convert CoreData model into SQL
Swift
1
star