forked from webdriverio/appium-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WebView.ts
87 lines (80 loc) · 2.97 KB
/
WebView.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
export const CONTEXT_REF = {
NATIVE: 'native',
WEBVIEW: 'webview',
};
const DOCUMENT_READY_STATE = {
COMPLETE: 'complete',
INTERACTIVE: 'interactive',
LOADING: 'loading',
};
class WebView {
/**
* Wait for the webview context to be loaded
*
* By default you have `NATIVE_APP` as the current context. If a webview is loaded it will be
* added to the current contexts and will looks something like this for iOS
* `["NATIVE_APP","WEBVIEW_28158.2"]`
* The number behind `WEBVIEW` will be a random number in random order.
*
* For Android you can get something like
* ["NATIVE_APP","WEBVIEW_com.wdiodemoapp", "WEBVIEW_com.chrome"]`.
* The string behind `WEBVIEW` will the package name of the app that holds
* the webview
*/
waitForWebViewContextLoaded () {
driver.waitUntil(
() => {
const currentContexts = this.getCurrentContexts();
return currentContexts.length > 1 &&
currentContexts.find(context => context.toLowerCase().includes(CONTEXT_REF.WEBVIEW)) !== 'undefined';
}, {
// Wait a max of 45 seconds. Reason for this high amount is that loading
// a webview for iOS might take longer
timeout: 45000,
timeoutMsg: 'Webview context not loaded',
interval: 100,
},
);
}
/**
* Switch to native or webview context
*/
switchToContext (context:string) {
// The first context will always be the NATIVE_APP,
// the second one will always be the WebdriverIO web page
driver.switchContext(this.getCurrentContexts()[context === CONTEXT_REF.NATIVE ? 0 : 1]);
}
/**
* Returns an object with the list of all available contexts
*/
getCurrentContexts ():string[] {
return driver.getContexts();
}
/**
* Wait for the document to be fully loaded
*/
waitForDocumentFullyLoaded () {
driver.waitUntil(
// A webpage can have multiple states, the ready state is the one we need to have.
// This looks like the same implementation as for the w3c implementation for `browser.url('https://webdriver.io')`
// That command also waits for the readiness of the page, see also the w3c specs
// https://www.w3.org/TR/webdriver/#dfn-waiting-for-the-navigation-to-complete
() => driver.execute(() => document.readyState) === DOCUMENT_READY_STATE.COMPLETE,
{
timeout: 15000,
timeoutMsg: 'Website not loaded',
interval: 100,
},
);
}
/**
* Wait for the website in the webview to be loaded
*/
waitForWebsiteLoaded () {
this.waitForWebViewContextLoaded();
this.switchToContext(CONTEXT_REF.WEBVIEW);
this.waitForDocumentFullyLoaded();
this.switchToContext(CONTEXT_REF.NATIVE);
}
}
export default WebView;