How to use back method in chromeless

Best JavaScript code snippet using chromeless

swipe-back.js

Source:swipe-back.js Github

copy

Full Screen

...290      // Update Route291      router.currentRoute = previousPage[0].f7Page.route;292      router.currentPage = previousPage[0];293      // Page before animation callback294      router.pageCallback('beforeOut', currentPage, currentNavbar, 'current', 'next', { route: currentPage[0].f7Page.route, swipeBack: true });295      router.pageCallback('beforeIn', previousPage, previousNavbar, 'previous', 'current', { route: previousPage[0].f7Page.route, swipeBack: true });296      $el.trigger('swipeback:beforechange', callbackData);297      router.emit('swipebackBeforeChange', callbackData);298    } else {299      $el.trigger('swipeback:beforereset', callbackData);300      router.emit('swipebackBeforeReset', callbackData);301    }302    currentPage.transitionEnd(() => {303      $([currentPage[0], previousPage[0]]).removeClass('page-transitioning page-transitioning-swipeback');304      if (dynamicNavbar) {305        currentNavElements.removeClass('navbar-transitioning').css({ opacity: '' }).transform('');306        previousNavElements.removeClass('navbar-transitioning').css({ opacity: '' }).transform('');307        if (activeNavBackIcon && activeNavBackIcon.length > 0) activeNavBackIcon.removeClass('navbar-transitioning');308        if (previousNavBackIcon && previousNavBackIcon.length > 0) previousNavBackIcon.removeClass('navbar-transitioning');309      }310      allowViewTouchMove = true;311      router.allowPageChange = true;312      if (pageChanged) {313        // Update History314        if (router.history.length === 1) {315          router.history.unshift(router.url);316        }317        router.history.pop();318        router.saveHistory();319        // Update push state320        if (params.pushState) {321          History.back();322        }323        // Page after animation callback324        router.pageCallback('afterOut', currentPage, currentNavbar, 'current', 'next', { route: currentPage[0].f7Page.route, swipeBack: true });325        router.pageCallback('afterIn', previousPage, previousNavbar, 'previous', 'current', { route: previousPage[0].f7Page.route, swipeBack: true });326        // Remove Old Page327        if (params.stackPages && router.initialPages.indexOf(currentPage[0]) >= 0) {328          currentPage.addClass('stacked');329          if (separateNavbar) {330            currentNavbar.addClass('stacked');331          }332        } else {333          router.pageCallback('beforeRemove', currentPage, currentNavbar, 'next', { swipeBack: true });334          router.removePage(currentPage);335          if (separateNavbar) {336            router.removeNavbar(currentNavbar);337          }338        }339        $el.trigger('swipeback:afterchange', callbackData);340        router.emit('swipebackAfterChange', callbackData);341        router.emit('routeChanged', router.currentRoute, router.previousRoute, router);342        if (params.preloadPreviousPage) {343          router.back(router.history[router.history.length - 2], { preload: true });344        }345      } else {346        $el.trigger('swipeback:afterreset', callbackData);347        router.emit('swipebackAfterReset', callbackData);348      }349      if (pageShadow && pageShadow.length > 0) pageShadow.remove();350      if (pageOpacity && pageOpacity.length > 0) pageOpacity.remove();351    });352  }353  function attachEvents() {354    const passiveListener = (app.touchEvents.start === 'touchstart' && Support.passiveListener) ? { passive: true, capture: false } : false;355    $el.on(app.touchEvents.start, handleTouchStart, passiveListener);356    app.on('touchmove:active', handleTouchMove);357    app.on('touchend:passive', handleTouchEnd);...

Full Screen

Full Screen

Bar.js

Source:Bar.js Github

copy

Full Screen

1/**2 * This component is used in {@link Ext.navigation.View} to control animations in the toolbar. You should never need to3 * interact with the component directly, unless you are subclassing it.4 * @private5 * @author Robert Dougan <rob@sencha.com>6 */7Ext.define('Ext.navigation.Bar', {8    extend: 'Ext.TitleBar',9    requires: [10        'Ext.Button',11        'Ext.Spacer'12    ],13    // private14    isToolbar: true,15    config: {16        /**17         * @cfg18         * @inheritdoc19         */20        baseCls: Ext.baseCSSPrefix + 'toolbar',21        /**22         * @cfg23         * @inheritdoc24         */25        cls: Ext.baseCSSPrefix + 'navigation-bar',26        /**27         * @cfg {String} ui28         * Style options for Toolbar. Either 'light' or 'dark'.29         * @accessor30         */31        ui: 'dark',32        /**33         * @cfg {String} title34         * The title of the toolbar. You should NEVER set this, it is used internally. You set the title of the35         * navigation bar by giving a navigation views children a title configuration.36         * @private37         * @accessor38         */39        title: null,40        /**41         * @cfg42         * @hide43         * @accessor44         */45        defaultType: 'button',46        /**47         * @cfg48         * @ignore49         * @accessor50         */51        layout: {52            type: 'hbox'53        },54        /**55         * @cfg {Array/Object} items The child items to add to this NavigationBar. The {@link #cfg-defaultType} of56         * a NavigationBar is {@link Ext.Button}, so you do not need to specify an `xtype` if you are adding57         * buttons.58         *59         * You can also give items a `align` configuration which will align the item to the `left` or `right` of60         * the NavigationBar.61         * @hide62         * @accessor63         */64        /**65         * @cfg {String} defaultBackButtonText66         * The text to be displayed on the back button if:67         * a) The previous view does not have a title68         * b) The {@link #useTitleForBackButtonText} configuration is true.69         * @private70         * @accessor71         */72        defaultBackButtonText: 'Back',73        /**74         * @cfg {Object} animation75         * @private76         * @accessor77         */78        animation: {79            duration: 30080        },81        /**82         * @cfg {Boolean} useTitleForBackButtonText83         * Set to false if you always want to display the {@link #defaultBackButtonText} as the text84         * on the back button. True if you want to use the previous views title.85         * @private86         * @accessor87         */88        useTitleForBackButtonText: null,89        /**90         * @cfg {Ext.navigation.View} view A reference to the navigation view this bar is linked to.91         * @private92         * @accessor93         */94        view: null,95        /**96         * @cfg {Boolean} androidAnimation Optionally enable CSS transforms on Android 297         * for NavigationBar animations.  Note that this may cause flickering if the98         * NavigationBar is hidden.99         * @accessor100         */101        android2Transforms: false,102        /**103         * @cfg {Ext.Button/Object} backButton The configuration for the back button104         * @private105         * @accessor106         */107        backButton: {108            align: 'left',109            ui: 'back',110            hidden: true111        }112    },113    /**114     * @event back115     * Fires when the back button was tapped.116     * @param {Ext.navigation.Bar} this This bar117     */118    /**119     * The minmum back button width allowed.120     * @private121     */122    minBackButtonWidth: 80,123    constructor: function(config) {124        config = config || {};125        if (!config.items) {126            config.items = [];127        }128        this.backButtonStack = [];129        this.activeAnimations = [];130        this.callParent([config]);131    },132    /**133     * @private134     */135    applyBackButton: function(config) {136        return Ext.factory(config, Ext.Button, this.getBackButton());137    },138    /**139     * @private140     */141    updateBackButton: function(newBackButton, oldBackButton) {142        if (oldBackButton) {143            this.remove(oldBackButton);144        }145        if (newBackButton) {146            this.add(newBackButton);147            newBackButton.on({148                scope: this,149                tap: this.onBackButtonTap150            });151        }152    },153    onBackButtonTap: function() {154        this.fireEvent('back', this);155    },156    /**157     * @private158     */159    updateView: function(newView) {160        var me = this,161            backButton = me.getBackButton(),162            innerItems, i, backButtonText, item, title;163        me.getItems();164        if (newView) {165            //update the back button stack with the current inner items of the view166            innerItems = newView.getInnerItems();167            for (i = 0; i < innerItems.length; i++) {168                item = innerItems[i];169                title = (item.getTitle) ? item.getTitle() : item.config.title;170                me.backButtonStack.push(title || '&nbsp;');171            }172            me.setTitle(me.getTitleText());173            backButtonText = me.getBackButtonText();174            if (backButtonText) {175                backButton.setText(backButtonText);176                backButton.show();177            }178        }179    },180    /**181     * @private182     */183    onViewAdd: function(view, item) {184        var me = this,185            backButtonStack = me.backButtonStack,186            hasPrevious, title;187        me.endAnimation();188        title = (item.getTitle) ? item.getTitle() : item.config.title;189        backButtonStack.push(title || '&nbsp;');190        hasPrevious = backButtonStack.length > 1;191        me.doChangeView(view, hasPrevious, false);192    },193    /**194     * @private195     */196    onViewRemove: function(view) {197        var me = this,198            backButtonStack = me.backButtonStack,199            hasPrevious;200        me.endAnimation();201        backButtonStack.pop();202        hasPrevious = backButtonStack.length > 1;203        me.doChangeView(view, hasPrevious, true);204    },205    /**206     * @private207     */208    doChangeView: function(view, hasPrevious, reverse) {209        var me = this,210            leftBox = me.leftBox,211            leftBoxElement = leftBox.element,212            titleComponent = me.titleComponent,213            titleElement = titleComponent.element,214            backButton = me.getBackButton(),215            titleText = me.getTitleText(),216            backButtonText = me.getBackButtonText(),217            animation = me.getAnimation() && view.getLayout().getAnimation(),218            animated = animation && animation.isAnimation && view.isPainted(),219            properties, leftGhost, titleGhost, leftProps, titleProps;220        if (animated) {221            leftGhost = me.createProxy(leftBox.element);222            leftBoxElement.setStyle('opacity', '0');223            backButton.setText(backButtonText);224            backButton[hasPrevious ? 'show' : 'hide']();225            titleGhost = me.createProxy(titleComponent.element.getParent());226            titleElement.setStyle('opacity', '0');227            me.setTitle(titleText);228            me.refreshTitlePosition();229            properties = me.measureView(leftGhost, titleGhost, reverse);230            leftProps = properties.left;231            titleProps = properties.title;232            me.isAnimating = true;233            me.animate(leftBoxElement, leftProps.element);234            me.animate(titleElement, titleProps.element, function() {235                titleElement.setLeft(properties.titleLeft);236                me.isAnimating = false;237            });238            if (Ext.os.is.Android2 && !this.getAndroid2Transforms()) {239                leftGhost.ghost.destroy();240                titleGhost.ghost.destroy();241            }242            else {243                me.animate(leftGhost.ghost, leftProps.ghost);244                me.animate(titleGhost.ghost, titleProps.ghost, function() {245                    leftGhost.ghost.destroy();246                    titleGhost.ghost.destroy();247                });248            }249        }250        else {251            if (hasPrevious) {252                backButton.setText(backButtonText);253                backButton.show();254            }255            else {256                backButton.hide();257            }258            me.setTitle(titleText);259        }260    },261    /**262     * Calculates and returns the position values needed for the back button when you are pushing a title.263     * @private264     */265    measureView: function(oldLeft, oldTitle, reverse) {266        var me = this,267            barElement = me.element,268            newLeftElement = me.leftBox.element,269            titleElement = me.titleComponent.element,270            minOffset = Math.min(barElement.getWidth() / 3, 200),271            newLeftWidth = newLeftElement.getWidth(),272            barX = barElement.getX(),273            barWidth = barElement.getWidth(),274            titleX = titleElement.getX(),275            titleLeft = titleElement.getLeft(),276            titleWidth = titleElement.getWidth(),277            oldLeftX = oldLeft.x,278            oldLeftWidth = oldLeft.width,279            oldLeftLeft = oldLeft.left,280            useLeft = Ext.os.is.Android2 && !this.getAndroid2Transforms(),281            newOffset, oldOffset, leftAnims, titleAnims, omega, theta;282        theta = barX - oldLeftX - oldLeftWidth;283        if (reverse) {284            newOffset = theta;285            oldOffset = Math.min(titleX - oldLeftWidth, minOffset);286        }287        else {288            oldOffset = theta;289            newOffset = Math.min(titleX - barX, minOffset);290        }291        if (useLeft) {292            leftAnims = {293                element: {294                    from: {295                        left: newOffset,296                        opacity: 1297                    },298                    to: {299                        left: 0,300                        opacity: 1301                    }302                }303            };304        }305        else {306            leftAnims = {307                element: {308                    from: {309                        transform: {310                            translateX: newOffset311                        },312                        opacity: 0313                    },314                    to: {315                        transform: {316                            translateX: 0317                        },318                        opacity: 1319                    }320                },321                ghost: {322                    to: {323                        transform: {324                            translateX: oldOffset325                        },326                        opacity: 0327                    }328                }329            };330        }331        theta = barX - titleX + newLeftWidth;332        if ((oldLeftLeft + titleWidth) > titleX) {333            omega = barX - titleX - titleWidth;334        }335        if (reverse) {336            titleElement.setLeft(0);337            oldOffset = barX + barWidth;338            if (omega !== undefined) {339                newOffset = omega;340            }341            else {342                newOffset = theta;343            }344        }345        else {346            newOffset = barWidth - titleX;347            if (omega !== undefined) {348                oldOffset = omega;349            }350            else {351                oldOffset = theta;352            }353        }354        if (useLeft) {355            titleAnims = {356                element: {357                    from: {358                        left: newOffset,359                        opacity: 1360                    },361                    to: {362                        left: titleLeft,363                        opacity: 1364                    }365                }366            };367        }368        else {369            titleAnims = {370                element: {371                    from: {372                        transform: {373                            translateX: newOffset374                        },375                        opacity: 0376                    },377                    to: {378                        transform: {379                            translateX: titleLeft380                        },381                        opacity: 1382                    }383                },384                ghost: {385                    to: {386                        transform: {387                            translateX: oldOffset388                        },389                        opacity: 0390                    }391                }392            };393        }394        return {395            left: leftAnims,396            title: titleAnims,397            titleLeft: titleLeft398        };399    },400    /**401     * Helper method used to animate elements.402     * You pass it an element, objects for the from and to positions an option onEnd callback called when the animation is over.403     * Normally this method is passed configurations returned from the methods such as #measureTitle(true) etc.404     * It is called from the #pushLeftBoxAnimated, #pushTitleAnimated, #popBackButtonAnimated and #popTitleAnimated405     * methods.406     *407     * If the current device is Android, it will use top/left to animate.408     * If it is anything else, it will use transform.409     * @private410     */411    animate: function(element, config, callback) {412        var me = this,413            animation;414        //reset the left of the element415        element.setLeft(0);416        config = Ext.apply(config, {417            element: element,418            easing: 'ease-in-out',419            duration: me.getAnimation().duration420        });421        animation = new Ext.fx.Animation(config);422        animation.on('animationend', function() {423            if (callback) {424                callback.call(me);425            }426        }, me);427        Ext.Animator.run(animation);428        me.activeAnimations.push(animation);429    },430    endAnimation: function() {431        var activeAnimations = this.activeAnimations,432            animation, i, ln;433        if (activeAnimations) {434            ln = activeAnimations.length;435            for (i = 0; i < ln; i++) {436                animation = activeAnimations[i];437                if (animation.isAnimating) {438                    animation.stopAnimation();439                }440                else {441                    animation.destroy();442                }443            }444            this.activeAnimations = [];445        }446    },447    refreshTitlePosition: function() {448        if (!this.isAnimating) {449            this.callParent();450        }451    },452    /**453     * Returns the text needed for the current back button at anytime.454     * @private455     */456    getBackButtonText: function() {457        var text = this.backButtonStack[this.backButtonStack.length - 2],458            useTitleForBackButtonText = this.getUseTitleForBackButtonText();459        if (!useTitleForBackButtonText) {460            if (text) {461                text = this.getDefaultBackButtonText();462            }463        }464        return text;465    },466    /**467     * Returns the text needed for the current title at anytime.468     * @private469     */470    getTitleText: function() {471        return this.backButtonStack[this.backButtonStack.length - 1];472    },473    /**474     * Handles removing back button stacks from this bar475     * @private476     */477    beforePop: function(count) {478        count--;479        for (var i = 0; i < count; i++) {480            this.backButtonStack.pop();481        }482    },483    /**484     * We override the hidden method because we don't want to remove it from the view using display:none. Instead we just position it off485     * the screen, much like the navigation bar proxy. This means that all animations, pushing, popping etc. all still work when if you hide/show486     * this bar at any time.487     * @private488     */489    doSetHidden: function(hidden) {490        if (!hidden) {491            this.element.setStyle({492                position: 'relative',493                top: 'auto',494                left: 'auto',495                width: 'auto'496            });497        } else {498            this.element.setStyle({499                position: 'absolute',500                top: '-1000px',501                left: '-1000px',502                width: this.element.getWidth() + 'px'503            });504        }505    },506    /**507     * Creates a proxy element of the passed element, and positions it in the same position, using absolute positioning.508     * The createNavigationBarProxy method uses this to create proxies of the backButton and the title elements.509     * @private510     */511    createProxy: function(element) {512        var ghost, x, y, left, width;513        ghost = element.dom.cloneNode(true);514        ghost.id = element.id + '-proxy';515        //insert it into the toolbar516        element.getParent().dom.appendChild(ghost);517        //set the x/y518        ghost = Ext.get(ghost);519        x = element.getX();520        y = element.getY();521        left = element.getLeft();522        width = element.getWidth();523        ghost.setStyle('position', 'absolute');524        ghost.setX(x);525        ghost.setY(y);526        ghost.setHeight(element.getHeight());527        ghost.setWidth(width);528        return {529            x: x,530            y: y,531            left: left,532            width: width,533            ghost: ghost534        };535    }...

Full Screen

Full Screen

back.js

Source:back.js Github

copy

Full Screen

1define(["./_base/config", "./_base/lang", "./sniff", "./dom", "./dom-construct", "./_base/window", "require"],2	function(config, lang, has, dom, domConstruct, baseWindow, require){3	// module:4	//		dojo/back5	var back = {6		// summary:7		//		Browser history management resources8	};9	has("extend-dojo") && lang.setObject("dojo.back", back);10	// everyone deals with encoding the hash slightly differently11	var getHash = back.getHash = function(){12		var h = window.location.hash;13		if(h.charAt(0) == "#"){ h = h.substring(1); }14		return has("mozilla") ? h : decodeURIComponent(h);15	},16	setHash = back.setHash = function(h){17		if(!h){ h = ""; }18		window.location.hash = encodeURIComponent(h);19		historyCounter = history.length;20	};21	var initialHref = (typeof(window) !== "undefined") ? window.location.href : "";22	var initialHash = (typeof(window) !== "undefined") ? getHash() : "";23	var initialState = null;24	var locationTimer = null;25	var bookmarkAnchor = null;26	var historyIframe = null;27	var forwardStack = [];28	var historyStack = [];29	var moveForward = false;30	var changingUrl = false;31	var historyCounter;32	function handleBackButton(){33		// summary:34		//		private method. Do not call this directly.35		//The "current" page is always at the top of the history stack.36		var current = historyStack.pop();37		if(!current){ return; }38		var last = historyStack[historyStack.length-1];39		if(!last && historyStack.length == 0){40			last = initialState;41		}42		if(last){43			if(last.kwArgs["back"]){44				last.kwArgs["back"]();45			}else if(last.kwArgs["backButton"]){46				last.kwArgs["backButton"]();47			}else if(last.kwArgs["handle"]){48				last.kwArgs.handle("back");49			}50		}51		forwardStack.push(current);52	}53	back.goBack = handleBackButton;54	function handleForwardButton(){55		// summary:56		//		private method. Do not call this directly.57		var last = forwardStack.pop();58		if(!last){ return; }59		if(last.kwArgs["forward"]){60			last.kwArgs.forward();61		}else if(last.kwArgs["forwardButton"]){62			last.kwArgs.forwardButton();63		}else if(last.kwArgs["handle"]){64			last.kwArgs.handle("forward");65		}66		historyStack.push(last);67	}68	back.goForward = handleForwardButton;69	function createState(url, args, hash){70		// summary:71		//		private method. Do not call this directly.72		return {"url": url, "kwArgs": args, "urlHash": hash};	//Object73	}74	function getUrlQuery(url){75		// summary:76		//		private method. Do not call this directly.77		var segments = url.split("?");78		if(segments.length < 2){79			return null; //null80		}81		else{82			return segments[1]; //String83		}84	}85	function loadIframeHistory(){86		// summary:87		//		private method. Do not call this directly.88		var url = (config["dojoIframeHistoryUrl"] || require.toUrl("./resources/iframe_history.html")) + "?" + (new Date()).getTime();89		moveForward = true;90		if(historyIframe){91			has("webkit") ? historyIframe.location = url : window.frames[historyIframe.name].location = url;92		}else{93			//console.warn("dojo/back: Not initialised. You need to call back.init() from a <script> block that lives inside the <body> tag.");94		}95		return url; //String96	}97	function checkLocation(){98		if(!changingUrl){99			var hsl = historyStack.length;100			var hash = getHash();101			if((hash === initialHash||window.location.href == initialHref)&&(hsl == 1)){102				// FIXME: could this ever be a forward button?103				// we can't clear it because we still need to check for forwards. Ugg.104				// clearInterval(this.locationTimer);105				handleBackButton();106				return;107			}108			// first check to see if we could have gone forward. We always halt on109			// a no-hash item.110			if(forwardStack.length > 0){111				if(forwardStack[forwardStack.length-1].urlHash === hash){112					handleForwardButton();113					return;114				}115			}116			// ok, that didn't work, try someplace back in the history stack117			if((hsl >= 2)&&(historyStack[hsl-2])){118				if(historyStack[hsl-2].urlHash === hash){119					handleBackButton();120				}121			}122		}123	}124	back.init = function(){125		// summary:126		//		Initializes the undo stack. This must be called from a <script>127		//		block that lives inside the `<body>` tag to prevent bugs on IE.128		//129		//		Only call this method before the page's DOM is finished loading. Otherwise130		//		it will not work. Be careful with xdomain loading or djConfig.debugAtAllCosts scenarios,131		//		in order for this method to work, dojo/back will need to be part of a build layer.132		// prevent reinit133		if(dom.byId("dj_history")){ return; } 134		var src = config["dojoIframeHistoryUrl"] || require.toUrl("./resources/iframe_history.html");135		if (config.afterOnLoad){136			console.error("dojo/back::init() must be called before the DOM has loaded. "137						+ "Include dojo/back in a build layer.");138		}else{139			document.write('<iframe style="border:0;width:1px;height:1px;position:absolute;visibility:hidden;bottom:0;right:0;" name="dj_history" id="dj_history" src="' + src + '"></iframe>');140		}141	};142	back.setInitialState = function(/*Object*/args){143		// summary:144		//		Sets the state object and back callback for the very first page145		//		that is loaded.146		//147		//		It is recommended that you call this method as part of an event148		//		listener that is registered via dojo/ready.149		// args: Object150		//		See the addToHistory() function for the list of valid args properties.151		initialState = createState(initialHref, args, initialHash);152	};153	//FIXME: Make these doc comments not be awful. At least they're not wrong.154	//FIXME: Would like to support arbitrary back/forward jumps. Have to rework iframeLoaded among other things.155	//FIXME: is there a slight race condition in moz using change URL with the timer check and when156	//		 the hash gets set? I think I have seen a back/forward call in quick succession, but not consistent.157	/*=====158	var __backArgs = {159		// back: Function?160		//		A function to be called when this state is reached via the user161		//		clicking the back button.162		// forward: Function?163		//		Upon return to this state from the "back, forward" combination164		//		of navigation steps, this function will be called. Somewhat165		//		analogous to the semantic of an "onRedo" event handler.166		// changeUrl: Boolean|String?167		//		Boolean indicating whether or not to create a unique hash for168		//		this state. If a string is passed instead, it is used as the169		//		hash.170	};171	=====*/172	back.addToHistory = function(args){173		// summary:174		//		adds a state object (args) to the history list.175		// args: __backArgs176		//		The state object that will be added to the history list.177		// description:178		//		To support getting back button notifications, the object179		//		argument should implement a function called either "back",180		//		"backButton", or "handle". The string "back" will be passed as181		//		the first and only argument to this callback.182		//183		//		To support getting forward button notifications, the object184		//		argument should implement a function called either "forward",185		//		"forwardButton", or "handle". The string "forward" will be186		//		passed as the first and only argument to this callback.187		//188		//		If you want the browser location string to change, define "changeUrl" on the object. If the189		//		value of "changeUrl" is true, then a unique number will be appended to the URL as a fragment190		//		identifier (http://some.domain.com/path#uniquenumber). If it is any other value that does191		//		not evaluate to false, that value will be used as the fragment identifier. For example,192		//		if changeUrl: 'page1', then the URL will look like: http://some.domain.com/path#page1193		//194		//		There are problems with using dojo/back with semantically-named fragment identifiers195		//		("hash values" on an URL). In most browsers it will be hard for dojo/back to know196		//		distinguish a back from a forward event in those cases. For back/forward support to197		//		work best, the fragment ID should always be a unique value (something using new Date().getTime()198		//		for example). If you want to detect hash changes using semantic fragment IDs, then199		//		consider using dojo/hash instead (in Dojo 1.4+).200		//201		// example:202		//		|	back.addToHistory({203		//		|		back: function(){ console.log('back pressed'); },204		//		|		forward: function(){ console.log('forward pressed'); },205		//		|		changeUrl: true206		//		|	});207		//	BROWSER NOTES:208		//	Safari 1.2:209		//	back button "works" fine, however it's not possible to actually210		//	DETECT that you've moved backwards by inspecting window.location.211		//	Unless there is some other means of locating.212		//	FIXME: perhaps we can poll on history.length?213		//	Safari 2.0.3+ (and probably 1.3.2+):214		//	works fine, except when changeUrl is used. When changeUrl is used,215		//	Safari jumps all the way back to whatever page was shown before216		//	the page that uses dojo.undo.browser support.217		//	IE 5.5 SP2:218		//	back button behavior is macro. It does not move back to the219		//	previous hash value, but to the last full page load. This suggests220		//	that the iframe is the correct way to capture the back button in221		//	these cases.222		//	Don't test this page using local disk for MSIE. MSIE will not create223		//	a history list for iframe_history.html if served from a file: URL.224		//	The XML served back from the XHR tests will also not be properly225		//	created if served from local disk. Serve the test pages from a web226		//	server to test in that browser.227		//	IE 6.0:228		//	same behavior as IE 5.5 SP2229		//	Firefox 1.0+:230		//	the back button will return us to the previous hash on the same231		//	page, thereby not requiring an iframe hack, although we do then232		//	need to run a timer to detect inter-page movement.233		//If addToHistory is called, then that means we prune the234		//forward stack -- the user went back, then wanted to235		//start a new forward path.236		forwardStack = [];237		var hash = null;238		var url = null;239		if(!historyIframe){240			if(config["useXDomain"] && !config["dojoIframeHistoryUrl"]){241				console.warn("dojo/back: When using cross-domain Dojo builds,"242					+ " please save iframe_history.html to your domain and set djConfig.dojoIframeHistoryUrl"243					+ " to the path on your domain to iframe_history.html");244			}245			historyIframe = window.frames["dj_history"];246		}247		if(!bookmarkAnchor){248			bookmarkAnchor = domConstruct.create("a", {style: {display: "none"}}, baseWindow.body());249		}250		if(args["changeUrl"]){251			hash = ""+ ((args["changeUrl"]!==true) ? args["changeUrl"] : (new Date()).getTime());252			//If the current hash matches the new one, just replace the history object with253			//this new one. It doesn't make sense to track different state objects for the same254			//logical URL. This matches the browser behavior of only putting in one history255			//item no matter how many times you click on the same #hash link, at least in Firefox256			//and Safari, and there is no reliable way in those browsers to know if a #hash link257			//has been clicked on multiple times. So making this the standard behavior in all browsers258			//so that dojo/back's behavior is the same in all browsers.259			if(historyStack.length == 0 && initialState.urlHash == hash){260				initialState = createState(url, args, hash);261				return;262			}else if(historyStack.length > 0 && historyStack[historyStack.length - 1].urlHash == hash){263				historyStack[historyStack.length - 1] = createState(url, args, hash);264				return;265			}266			changingUrl = true;267			setTimeout(function(){268					setHash(hash);269					changingUrl = false;270				}, 1);271			bookmarkAnchor.href = hash;272			if(has("ie")){273				url = loadIframeHistory();274				var oldCB = args["back"]||args["backButton"]||args["handle"];275				//The function takes handleName as a parameter, in case the276				//callback we are overriding was "handle". In that case,277				//we will need to pass the handle name to handle.278				var tcb = function(handleName){279					if(getHash() != ""){280						setTimeout(function(){ setHash(hash); }, 1);281					}282					//Use apply to set "this" to args, and to try to avoid memory leaks.283					oldCB.apply(this, [handleName]);284				};285				//Set interceptor function in the right place.286				if(args["back"]){287					args.back = tcb;288				}else if(args["backButton"]){289					args.backButton = tcb;290				}else if(args["handle"]){291					args.handle = tcb;292				}293				var oldFW = args["forward"]||args["forwardButton"]||args["handle"];294				//The function takes handleName as a parameter, in case the295				//callback we are overriding was "handle". In that case,296				//we will need to pass the handle name to handle.297				var tfw = function(handleName){298					if(getHash() != ""){299						setHash(hash);300					}301					if(oldFW){ // we might not actually have one302						//Use apply to set "this" to args, and to try to avoid memory leaks.303						oldFW.apply(this, [handleName]);304					}305				};306				//Set interceptor function in the right place.307				if(args["forward"]){308					args.forward = tfw;309				}else if(args["forwardButton"]){310					args.forwardButton = tfw;311				}else if(args["handle"]){312					args.handle = tfw;313				}314			}else if(!has("ie")){315				// start the timer316				if(!locationTimer){317					locationTimer = setInterval(checkLocation, 200);318				}319			}320		}else{321			url = loadIframeHistory();322		}323		historyStack.push(createState(url, args, hash));324	};325	back._iframeLoaded = function(evt, ifrLoc){326		// summary:327		//		private method. Do not call this directly.328		var query = getUrlQuery(ifrLoc.href);329		if(query == null){330			// alert("iframeLoaded");331			// we hit the end of the history, so we should go back332			if(historyStack.length == 1){333				handleBackButton();334			}335			return;336		}337		if(moveForward){338			// we were expecting it, so it's not either a forward or backward movement339			moveForward = false;340			return;341		}342		//Check the back stack first, since it is more likely.343		//Note that only one step back or forward is supported.344		if(historyStack.length >= 2 && query == getUrlQuery(historyStack[historyStack.length-2].url)){345			handleBackButton();346		}else if(forwardStack.length > 0 && query == getUrlQuery(forwardStack[forwardStack.length-1].url)){347			handleForwardButton();348		}349	};350	return back;351	...

Full Screen

Full Screen

back.js.uncompressed.js

Source:back.js.uncompressed.js Github

copy

Full Screen

1define("dojo/back", ["./_base/config", "./_base/lang", "./sniff", "./dom", "./dom-construct", "./_base/window", "require"],2	function(config, lang, has, dom, domConstruct, baseWindow, require){3	// module:4	//		dojo/back5	var back = {6		// summary:7		//		Browser history management resources8	};9	 1  && lang.setObject("dojo.back", back);10	// everyone deals with encoding the hash slightly differently11	var getHash = back.getHash = function(){12		var h = window.location.hash;13		if(h.charAt(0) == "#"){ h = h.substring(1); }14		return has("mozilla") ? h : decodeURIComponent(h);15	},16	setHash = back.setHash = function(h){17		if(!h){ h = ""; }18		window.location.hash = encodeURIComponent(h);19		historyCounter = history.length;20	};21	var initialHref = (typeof(window) !== "undefined") ? window.location.href : "";22	var initialHash = (typeof(window) !== "undefined") ? getHash() : "";23	var initialState = null;24	var locationTimer = null;25	var bookmarkAnchor = null;26	var historyIframe = null;27	var forwardStack = [];28	var historyStack = [];29	var moveForward = false;30	var changingUrl = false;31	var historyCounter;32	function handleBackButton(){33		// summary:34		//		private method. Do not call this directly.35		//The "current" page is always at the top of the history stack.36		var current = historyStack.pop();37		if(!current){ return; }38		var last = historyStack[historyStack.length-1];39		if(!last && historyStack.length == 0){40			last = initialState;41		}42		if(last){43			if(last.kwArgs["back"]){44				last.kwArgs["back"]();45			}else if(last.kwArgs["backButton"]){46				last.kwArgs["backButton"]();47			}else if(last.kwArgs["handle"]){48				last.kwArgs.handle("back");49			}50		}51		forwardStack.push(current);52	}53	back.goBack = handleBackButton;54	function handleForwardButton(){55		// summary:56		//		private method. Do not call this directly.57		var last = forwardStack.pop();58		if(!last){ return; }59		if(last.kwArgs["forward"]){60			last.kwArgs.forward();61		}else if(last.kwArgs["forwardButton"]){62			last.kwArgs.forwardButton();63		}else if(last.kwArgs["handle"]){64			last.kwArgs.handle("forward");65		}66		historyStack.push(last);67	}68	back.goForward = handleForwardButton;69	function createState(url, args, hash){70		// summary:71		//		private method. Do not call this directly.72		return {"url": url, "kwArgs": args, "urlHash": hash};	//Object73	}74	function getUrlQuery(url){75		// summary:76		//		private method. Do not call this directly.77		var segments = url.split("?");78		if(segments.length < 2){79			return null; //null80		}81		else{82			return segments[1]; //String83		}84	}85	function loadIframeHistory(){86		// summary:87		//		private method. Do not call this directly.88		var url = (config["dojoIframeHistoryUrl"] || require.toUrl("./resources/iframe_history.html")) + "?" + (new Date()).getTime();89		moveForward = true;90		if(historyIframe){91			has("webkit") ? historyIframe.location = url : window.frames[historyIframe.name].location = url;92		}else{93			//console.warn("dojo/back: Not initialised. You need to call back.init() from a <script> block that lives inside the <body> tag.");94		}95		return url; //String96	}97	function checkLocation(){98		if(!changingUrl){99			var hsl = historyStack.length;100			var hash = getHash();101			if((hash === initialHash||window.location.href == initialHref)&&(hsl == 1)){102				// FIXME: could this ever be a forward button?103				// we can't clear it because we still need to check for forwards. Ugg.104				// clearInterval(this.locationTimer);105				handleBackButton();106				return;107			}108			// first check to see if we could have gone forward. We always halt on109			// a no-hash item.110			if(forwardStack.length > 0){111				if(forwardStack[forwardStack.length-1].urlHash === hash){112					handleForwardButton();113					return;114				}115			}116			// ok, that didn't work, try someplace back in the history stack117			if((hsl >= 2)&&(historyStack[hsl-2])){118				if(historyStack[hsl-2].urlHash === hash){119					handleBackButton();120				}121			}122		}123	}124	back.init = function(){125		// summary:126		//		Initializes the undo stack. This must be called from a <script>127		//		block that lives inside the `<body>` tag to prevent bugs on IE.128		//129		//		Only call this method before the page's DOM is finished loading. Otherwise130		//		it will not work. Be careful with xdomain loading or djConfig.debugAtAllCosts scenarios,131		//		in order for this method to work, dojo/back will need to be part of a build layer.132		// prevent reinit133		if(dom.byId("dj_history")){ return; } 134		var src = config["dojoIframeHistoryUrl"] || require.toUrl("./resources/iframe_history.html");135		if (config.afterOnLoad){136			console.error("dojo/back::init() must be called before the DOM has loaded. "137						+ "Include dojo/back in a build layer.");138		}else{139			document.write('<iframe style="border:0;width:1px;height:1px;position:absolute;visibility:hidden;bottom:0;right:0;" name="dj_history" id="dj_history" src="' + src + '"></iframe>');140		}141	};142	back.setInitialState = function(/*Object*/args){143		// summary:144		//		Sets the state object and back callback for the very first page145		//		that is loaded.146		//147		//		It is recommended that you call this method as part of an event148		//		listener that is registered via dojo/ready.149		// args: Object150		//		See the addToHistory() function for the list of valid args properties.151		initialState = createState(initialHref, args, initialHash);152	};153	//FIXME: Make these doc comments not be awful. At least they're not wrong.154	//FIXME: Would like to support arbitrary back/forward jumps. Have to rework iframeLoaded among other things.155	//FIXME: is there a slight race condition in moz using change URL with the timer check and when156	//		 the hash gets set? I think I have seen a back/forward call in quick succession, but not consistent.157	/*=====158	var __backArgs = {159		// back: Function?160		//		A function to be called when this state is reached via the user161		//		clicking the back button.162		// forward: Function?163		//		Upon return to this state from the "back, forward" combination164		//		of navigation steps, this function will be called. Somewhat165		//		analogous to the semantic of an "onRedo" event handler.166		// changeUrl: Boolean|String?167		//		Boolean indicating whether or not to create a unique hash for168		//		this state. If a string is passed instead, it is used as the169		//		hash.170	};171	=====*/172	back.addToHistory = function(args){173		// summary:174		//		adds a state object (args) to the history list.175		// args: __backArgs176		//		The state object that will be added to the history list.177		// description:178		//		To support getting back button notifications, the object179		//		argument should implement a function called either "back",180		//		"backButton", or "handle". The string "back" will be passed as181		//		the first and only argument to this callback.182		//183		//		To support getting forward button notifications, the object184		//		argument should implement a function called either "forward",185		//		"forwardButton", or "handle". The string "forward" will be186		//		passed as the first and only argument to this callback.187		//188		//		If you want the browser location string to change, define "changeUrl" on the object. If the189		//		value of "changeUrl" is true, then a unique number will be appended to the URL as a fragment190		//		identifier (http://some.domain.com/path#uniquenumber). If it is any other value that does191		//		not evaluate to false, that value will be used as the fragment identifier. For example,192		//		if changeUrl: 'page1', then the URL will look like: http://some.domain.com/path#page1193		//194		//		There are problems with using dojo/back with semantically-named fragment identifiers195		//		("hash values" on an URL). In most browsers it will be hard for dojo/back to know196		//		distinguish a back from a forward event in those cases. For back/forward support to197		//		work best, the fragment ID should always be a unique value (something using new Date().getTime()198		//		for example). If you want to detect hash changes using semantic fragment IDs, then199		//		consider using dojo/hash instead (in Dojo 1.4+).200		//201		// example:202		//		|	back.addToHistory({203		//		|		back: function(){ console.log('back pressed'); },204		//		|		forward: function(){ console.log('forward pressed'); },205		//		|		changeUrl: true206		//		|	});207		//	BROWSER NOTES:208		//	Safari 1.2:209		//	back button "works" fine, however it's not possible to actually210		//	DETECT that you've moved backwards by inspecting window.location.211		//	Unless there is some other means of locating.212		//	FIXME: perhaps we can poll on history.length?213		//	Safari 2.0.3+ (and probably 1.3.2+):214		//	works fine, except when changeUrl is used. When changeUrl is used,215		//	Safari jumps all the way back to whatever page was shown before216		//	the page that uses dojo.undo.browser support.217		//	IE 5.5 SP2:218		//	back button behavior is macro. It does not move back to the219		//	previous hash value, but to the last full page load. This suggests220		//	that the iframe is the correct way to capture the back button in221		//	these cases.222		//	Don't test this page using local disk for MSIE. MSIE will not create223		//	a history list for iframe_history.html if served from a file: URL.224		//	The XML served back from the XHR tests will also not be properly225		//	created if served from local disk. Serve the test pages from a web226		//	server to test in that browser.227		//	IE 6.0:228		//	same behavior as IE 5.5 SP2229		//	Firefox 1.0+:230		//	the back button will return us to the previous hash on the same231		//	page, thereby not requiring an iframe hack, although we do then232		//	need to run a timer to detect inter-page movement.233		//If addToHistory is called, then that means we prune the234		//forward stack -- the user went back, then wanted to235		//start a new forward path.236		forwardStack = [];237		var hash = null;238		var url = null;239		if(!historyIframe){240			if(config["useXDomain"] && !config["dojoIframeHistoryUrl"]){241				console.warn("dojo/back: When using cross-domain Dojo builds,"242					+ " please save iframe_history.html to your domain and set djConfig.dojoIframeHistoryUrl"243					+ " to the path on your domain to iframe_history.html");244			}245			historyIframe = window.frames["dj_history"];246		}247		if(!bookmarkAnchor){248			bookmarkAnchor = domConstruct.create("a", {style: {display: "none"}}, baseWindow.body());249		}250		if(args["changeUrl"]){251			hash = ""+ ((args["changeUrl"]!==true) ? args["changeUrl"] : (new Date()).getTime());252			//If the current hash matches the new one, just replace the history object with253			//this new one. It doesn't make sense to track different state objects for the same254			//logical URL. This matches the browser behavior of only putting in one history255			//item no matter how many times you click on the same #hash link, at least in Firefox256			//and Safari, and there is no reliable way in those browsers to know if a #hash link257			//has been clicked on multiple times. So making this the standard behavior in all browsers258			//so that dojo/back's behavior is the same in all browsers.259			if(historyStack.length == 0 && initialState.urlHash == hash){260				initialState = createState(url, args, hash);261				return;262			}else if(historyStack.length > 0 && historyStack[historyStack.length - 1].urlHash == hash){263				historyStack[historyStack.length - 1] = createState(url, args, hash);264				return;265			}266			changingUrl = true;267			setTimeout(function(){268					setHash(hash);269					changingUrl = false;270				}, 1);271			bookmarkAnchor.href = hash;272			if(has("ie")){273				url = loadIframeHistory();274				var oldCB = args["back"]||args["backButton"]||args["handle"];275				//The function takes handleName as a parameter, in case the276				//callback we are overriding was "handle". In that case,277				//we will need to pass the handle name to handle.278				var tcb = function(handleName){279					if(getHash() != ""){280						setTimeout(function(){ setHash(hash); }, 1);281					}282					//Use apply to set "this" to args, and to try to avoid memory leaks.283					oldCB.apply(this, [handleName]);284				};285				//Set interceptor function in the right place.286				if(args["back"]){287					args.back = tcb;288				}else if(args["backButton"]){289					args.backButton = tcb;290				}else if(args["handle"]){291					args.handle = tcb;292				}293				var oldFW = args["forward"]||args["forwardButton"]||args["handle"];294				//The function takes handleName as a parameter, in case the295				//callback we are overriding was "handle". In that case,296				//we will need to pass the handle name to handle.297				var tfw = function(handleName){298					if(getHash() != ""){299						setHash(hash);300					}301					if(oldFW){ // we might not actually have one302						//Use apply to set "this" to args, and to try to avoid memory leaks.303						oldFW.apply(this, [handleName]);304					}305				};306				//Set interceptor function in the right place.307				if(args["forward"]){308					args.forward = tfw;309				}else if(args["forwardButton"]){310					args.forwardButton = tfw;311				}else if(args["handle"]){312					args.handle = tfw;313				}314			}else if(!has("ie")){315				// start the timer316				if(!locationTimer){317					locationTimer = setInterval(checkLocation, 200);318				}319			}320		}else{321			url = loadIframeHistory();322		}323		historyStack.push(createState(url, args, hash));324	};325	back._iframeLoaded = function(evt, ifrLoc){326		// summary:327		//		private method. Do not call this directly.328		var query = getUrlQuery(ifrLoc.href);329		if(query == null){330			// alert("iframeLoaded");331			// we hit the end of the history, so we should go back332			if(historyStack.length == 1){333				handleBackButton();334			}335			return;336		}337		if(moveForward){338			// we were expecting it, so it's not either a forward or backward movement339			moveForward = false;340			return;341		}342		//Check the back stack first, since it is more likely.343		//Note that only one step back or forward is supported.344		if(historyStack.length >= 2 && query == getUrlQuery(historyStack[historyStack.length-2].url)){345			handleBackButton();346		}else if(forwardStack.length > 0 && query == getUrlQuery(forwardStack[forwardStack.length-1].url)){347			handleForwardButton();348		}349	};350	return back;351	...

Full Screen

Full Screen

nav.service.js

Source:nav.service.js Github

copy

Full Screen

1/*jslint node: true */2'use strict';3angular.module('canvassTrac')4  .config(['$provide', 'IONIC_BACK_PRIORITY', function ($provide, IONIC_BACK_PRIORITY) {5    var priority = angular.copy(IONIC_BACK_PRIORITY);6    priority.app_exit = IONIC_BACK_PRIORITY.view + 1; // priority for app exit prompt7    priority.view_override = IONIC_BACK_PRIORITY.view + 2; // 1st priority for any view override8    priority.modal_override = IONIC_BACK_PRIORITY.modal + 1; // 1st priority for any modal override9    $provide.constant('BACK_PRIORITY', priority);10  }])11  .service('navService', navService);12/* Manually Identify Dependencies13  https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#style-y09114*/15navService.$inject = ['$state', '$rootScope', '$ionicHistory', '$ionicPlatform', '$ionicPopup', 'BACK_PRIORITY', 'consoleService', 'miscUtilFactory', 'USER', 'DBG'];16function navService($state, $rootScope, $ionicHistory, $ionicPlatform, $ionicPopup, BACK_PRIORITY, consoleService, miscUtilFactory, USER, DBG) {17  this.con = consoleService.getLogger('navService');18  this.ionicSoftBack = $rootScope.$ionicGoBack;   // save ref to ionic's soft back button function19  /**20   * Go back to the specified state21   * @param {string} state  State to go back to22   * @param {object} params           A map of the parameters that will be sent to the state23   * @see https://ui-router.github.io/ng1/docs/0.2.10/#/api/ui.router.state.$state24   * @param {object} nextViewOptions  Sets options for the next view25   * @see https://ionicframework.com/docs/v1/api/service/$ionicHistory/26   * @return {number} number of steps back taken27   */28  this.goBackTo = function (state, params, nextViewOptions) {29    var backCount = 0,30      view = this.findInHistory(function (entry) {31      return (entry.stateName === state);32    });33    if (view) {34      var count = view.index - $ionicHistory.currentView().index;35      backCount = this.goBack(count, params, nextViewOptions);36    }37    return backCount;38  };39  /**40   * Get the current history41   * @returns {object} Current history42   */43  this.getCurrentHistory = function () {44    return $ionicHistory.viewHistory().histories[$ionicHistory.currentHistoryId()];45  };46  /**47   * Find an entry in the current history stack48   * @param {function} test Function to use to locate the required entry49   * @returns {object} Required entry or null if not found50   */51  this.findInHistory = function (test) {52    var history = this.getCurrentHistory(),53      view;54    if (history) {55      view = history.stack.find(test);56    }57    return view;58  };59  /**60   * Go back the specified number of steps in the current history61   * @param {number} backCount  Number of steps to go back62   * @param {object} params           A map of the parameters that will be sent to the state63   * @see https://ui-router.github.io/ng1/docs/0.2.10/#/api/ui.router.state.$state64   * @param {object} nextViewOptions  Sets options for the next view65   * @see https://ionicframework.com/docs/v1/api/service/$ionicHistory/66   * @return {number} number of steps back taken67   */68  this.goBack = function (backCount, params, nextViewOptions) {69    if (typeof backCount === 'object') {70      nextViewOptions = params;71      params = backCount;72      backCount = -1;73    }74    this.con.debug('goBack ' + backCount);75    if (backCount < 0) {76      if (miscUtilFactory.isObject(params)) {77        var history = this.getCurrentHistory(),78          idx = ($ionicHistory.currentView().index + backCount);79        if ((idx >= 0) && (idx < history.stack.length)) {80          // update previous view's stateParams81          miscUtilFactory.copyProperties(params, history.stack[idx].stateParams);82        }83      }84      this.nextViewOptions(nextViewOptions);85      $ionicHistory.goBack(backCount);  // go back to view86    }87    return backCount;88  };89  /**90   * Wrapper for ui-router's go function91   * @param {string} to               Absolute state name or relative state path.92   * @param {object} params           A map of the parameters that will be sent to the state93   * @param {object} options          Options object94   * @see https://ui-router.github.io/ng1/docs/0.2.10/#/api/ui.router.state.$state95   * @param {object} nextViewOptions  Sets options for the next view96   * @see https://ionicframework.com/docs/v1/api/service/$ionicHistory/97   */98  this.go = function (to, params, options, nextViewOptions) {99    this.nextViewOptions(nextViewOptions);100    $state.go(to, params, options).then(this.dumpHistory.bind(this, 'Go to ' + to));101  };102  /**103   * Wrapper for $ionicHistory's nextViewOptions function104   * @param {object} options  Sets options for the next view105   * @see https://ionicframework.com/docs/v1/api/service/$ionicHistory/106   */107  this.nextViewOptions = function (options) {108    if (miscUtilFactory.isObject(options)) {109      $ionicHistory.nextViewOptions(options);110    }111  };112  /**113   * Initialises a back button control action114   * @param {object} scope115   * @param {function} fn     Called when the back button is pressed, if this listener is the highest priority.116   * @param {number} priority Only the highest priority will execute.117   * @param {*=} actionId     The id to assign this action. Default: a random unique id.118   * @returns {function} A function that, when called, will deregister this backButtonAction.119   * @see http://ionicframework.com/docs/v1/api/service/$ionicPlatform/120   */121  this.initForBackButtonAction = function (scope, fn, priority, actionId) {122    var backButtonActionCtrl = this.getBackButtonActionCtrl();123    // register back button function and save deregister function124    backButtonActionCtrl.func = this.registerBackButtonAction(fn, priority, actionId);125    backButtonActionCtrl.priority = priority;126    backButtonActionCtrl.actionId = actionId;127    // make sure its uninstalled when we leave the view128    scope.$on('$ionicView.leave', backButtonActionCtrl.eventHandler.bind(backButtonActionCtrl));129    return backButtonActionCtrl;130  };131  /**132   * Get standard object for back button control133   * @returns {object}134   */135  this.getBackButtonActionCtrl = function () {136    return {137      func: undefined,   // function provided by $ionicPlatform to deregister a custom back key action138      priority: undefined,  // registered priority139      actionId: undefined,  // id if provided during registeration140      eventHandler: function (e) {  // ionic event handler141        if (this.func) {142          this.func();  // deregister custom action143        }144        this.func = undefined;145      }146    };147  };148  /**149   * Wrapper for $ionicPlatform.registerBackButtonAction150   * @param {function} fn     Called when the back button is pressed, if this listener is the highest priority.151   * @param {number} priority Only the highest priority will execute.152   * @param {*=} actionId     The id to assign this action. Default: a random unique id.153   * @returns {function} A function that, when called, will deregister this backButtonAction.154   * @see http://ionicframework.com/docs/v1/api/service/$ionicPlatform/155   */156  this.registerBackButtonAction = function (fn, priority, actionId) {157    this.con.debug('registerBackButtonAction: ' + priority + ' ' + actionId);158    return $ionicPlatform.registerBackButtonAction(fn, priority, actionId);159  };160  // this is the default ionic soft back function161  //$rootScope.$ionicGoBack = function (backCount) {162  //  $ionicHistory.goBack(backCount);163  //};164  // Triggered when devices with a hardware back button (Android) is clicked by the user165  // This is a Cordova/Phonegap platform specifc method copied from ionic.bundle.js166  this.onHardwareBackButton = function (e) {167    var backView = $ionicHistory.backView();168    if (backView) {169      // there is a back view, go to it170      backView.go();171    } else {172      if (USER.authenticated) {173        // user logged in, so cnfirm exit174        $ionicPopup.confirm({175          title: 'Exit Application',176          template: 'Are you sure you want to exit?',177          cancelText: 'No',178          okText: 'Yes'179        }).then(function(res) {180          if(res) {181            ionic.Platform.exitApp();182          }183        });184      } else {185        // there is no back view, so close the app instead186        ionic.Platform.exitApp();187      }188    }189    e.preventDefault();190    return false;191  }192  /**193   * Register the app-specific back button action, overriding the default194   * @returns {function} A function that, when called, will deregister this backButtonAction.195   * @see http://ionicframework.com/docs/v1/api/service/$ionicPlatform/196   */197  this.registerAppBackButtonAction = function () {198    return this.registerBackButtonAction(this.onHardwareBackButton, BACK_PRIORITY.app_exit, 'app_exit');199  };200  /**201   * Dump the current history202   * @param {string} label  Optional label to display203   */204  this.dumpHistory = function (label) {205    if (this.con.isEnabled()) {206      var viewHistory = $ionicHistory.viewHistory(),207        currentView = $ionicHistory.currentView(),208        backView = $ionicHistory.backView(),209        forwardView = $ionicHistory.forwardView(),210        prop,211        view,212        history,213        marker;214      this.con.debug('--------------------');215      if (label) {216        this.con.debug(label);217      }218      for (prop in viewHistory.histories) {219        history = viewHistory.histories[prop];220        this.con.debug('history ' + history.historyId + ': stack ' + history.stack.length + ' parent ' + history.parentHistoryId);221        history.stack.forEach(function (view) {222          if (view === currentView) {223            marker = 'C';224          } else if (view === backView) {225            marker = 'B';226          } else if (view === forwardView) {227            marker = 'F';228          } else {229            marker = ' ';230          }231          this.con.debug('  ' + marker + ' ' + view.index + ': ' + view.viewId + ' ' + view.stateName + 232                            '  ' + (view.backViewId ? view.backViewId : 'x') + '<- ->' +233                            (view.forwardViewId ? view.forwardViewId : 'x'));234        }, this);235      }236      for (prop in viewHistory.views) {237        view = viewHistory.views[prop];238        this.con.debug('views ' + view.index + ': ' + view.viewId + ' ' + view.stateName);239      }240      this.con.debug('--------------------');241    }242  };...

Full Screen

Full Screen

KeyboardEventsSpec.js

Source:KeyboardEventsSpec.js Github

copy

Full Screen

1describe('Keyboard events feature', function() {2  'use strict';3  var $input1,4    $input2,5    $input3,6    $timepicker1,7    $timepicker2,8    $timepicker3,9    tp1,10    tp2,11    tp3;12  beforeEach(function () {13    loadFixtures('timepicker.html');14    $input1 = $('#timepicker1');15    $timepicker1 = $input1.timepicker();16    tp1 = $timepicker1.data('timepicker');17    $input2 = $('#timepicker2');18    $timepicker2 = $input2.timepicker({19      template: 'modal',20      showSeconds: true,21      minuteStep: 30,22      secondStep: 30,23      defaultTime: false24    });25    tp2 = $timepicker2.data('timepicker');26    $input3 = $('#timepicker3');27    $timepicker3 = $input3.timepicker({28      defaultTime: '23:15:20',29      showMeridian: false,30      showSeconds: true,31      template: false32    });33    tp3 = $timepicker3.data('timepicker');34  });35  afterEach(function () {36    $input1.data('timepicker').remove();37    $input2.data('timepicker').remove();38    $input3.data('timepicker').remove();39    $input1.remove();40    $input2.remove();41    $input3.remove();42  });43  it('should be able to control element by the arrow keys', function() {44    tp1.setTime('11:30 AM');45    tp1.update();46    $input1.trigger('focus');47    if (tp1.highlightedUnit !== 'hour') {48      tp1.highlightHour();49    }50    expect(tp1.highlightedUnit).toBe('hour', 'hour should be highlighted by default');51    // hours52    $input1.trigger({53      'type': 'keydown',54      'keyCode': 38 //up55    });56    expect(tp1.getTime()).toBe('12:30 PM', '1');57    $input1.trigger({58      'type': 'keydown',59      'keyCode': 40 //down60    });61    expect(tp1.getTime()).toBe('11:30 AM', '2');62    expect(tp1.highlightedUnit).toBe('hour', 'hour should be highlighted');63    $input1.trigger({64      'type': 'keydown',65      'keyCode': 39 //right66    });67    expect(tp1.highlightedUnit).toBe('minute', 'minute should be highlighted');68    //minutes69    $input1.trigger({70      'type': 'keydown',71      'keyCode': 38 //up72    });73    expect(tp1.getTime()).toBe('11:45 AM', '3');74    expect(tp1.highlightedUnit).toBe('minute', 'minute should be highlighted 1');75    $input1.trigger({76      'type': 'keydown',77      'keyCode': 40 //down78    });79    expect(tp1.getTime()).toBe('11:30 AM', '4');80    expect(tp1.highlightedUnit).toBe('minute', 'minute should be highlighted 2');81    $input1.trigger({82      'type': 'keydown',83      'keyCode': 39 //right84    });85    expect(tp1.highlightedUnit).toBe('meridian', 'meridian should be highlighted');86    //meridian87    $input1.trigger({88      'type': 'keydown',89      'keyCode': 38 //up90    });91    expect(tp1.getTime()).toBe('11:30 PM', '5');92    expect(tp1.highlightedUnit).toBe('meridian', 'meridian should be highlighted');93    $input1.trigger({94      'type': 'keydown',95      'keyCode': 40 //down96    });97    expect(tp1.getTime()).toBe('11:30 AM', '6');98    expect(tp1.highlightedUnit).toBe('meridian', 'meridian should be highlighted');99    $input1.trigger({100      'type': 'keydown',101      'keyCode': 37 //left102    });103    expect(tp1.highlightedUnit).toBe('minute', 'minutes should be highlighted');104    // minutes105    $input1.trigger({106      'type': 'keydown',107      'keyCode': 40 //down108    });109    expect(tp1.getTime()).toBe('11:15 AM', '7');110    $input1.trigger({111      'type': 'keydown',112      'keyCode': 37 //left113    });114    expect(tp1.highlightedUnit).toBe('hour', 'hours should be highlighted');115    // hours116    $input1.trigger({117      'type': 'keydown',118      'keyCode': 40 //down119    });120    expect(tp1.getTime()).toBe('10:15 AM', '8');121    $input1.trigger({122      'type': 'keydown',123      'keyCode': 37 //left124    });125    expect(tp1.highlightedUnit).toBe('meridian', 'meridian should be highlighted');126    // meridian127    $input1.trigger({128      'type': 'keydown',129      'keyCode': 40 //down130    });131    expect(tp1.getTime()).toBe('10:15 PM', '9');132  });133  it('should be able to change time via widget inputs in a dropdown', function() {134    var $hourInput = tp1.$widget.find('input.bootstrap-timepicker-hour'),135        $minuteInput = tp1.$widget.find('input.bootstrap-timepicker-minute'),136        $meridianInput = tp1.$widget.find('input.bootstrap-timepicker-meridian'),137        eventCount = 0,138        time;139    tp1.setTime('9:30 AM');140    tp1.update();141    $input1.parents('div').find('.add-on').click();142    $input1.timepicker().on('changeTime.timepicker', function(e) {143      eventCount++;144      time = e.time.value;145    });146    expect(tp1.isOpen).toBe(true);147    $hourInput.trigger('focus');148    $hourInput.autotype('{{back}}{{back}}11{{tab}}');149    expect(tp1.hour).toBe(11);150    expect(eventCount).toBe(1, 'incorrect update events thrown');151    expect(time).toBe('11:30 AM');152    $minuteInput.autotype('{{back}}{{back}}45{{tab}}');153    expect(tp1.minute).toBe(45);154    expect(eventCount).toBe(2, 'incorrect update events thrown');155    expect(time).toBe('11:45 AM');156    $meridianInput.autotype('{{back}}{{back}}pm{{tab}}');157    expect(tp1.meridian).toBe('PM');158    expect(eventCount).toBe(3, 'incorrect update events thrown');159    expect(time).toBe('11:45 PM');160  });161  it('should still be empty if input is empty', function() {162		$input1.autotype('{{back}}{{back}}{{back}}{{back}}{{back}}{{back}}{{back}}{{back}}{{tab}}');163		expect($input1.val()).toBe('');164	});165  it('should allow time to be changed via widget inputs in a modal', function() {166    //tp2.setTime('9:30 AM');167    //tp2.update();168    //$input2.parents('div').find('.add-on').click();169    //var $hourInput = $('body').find('input.bootstrap-timepicker-hour'),170        //$minuteInput = $('body').find('input.bootstrap-timepicker-minute'),171        //$secondInput = $('body').find('input.bootstrap-timepicker-second'),172        //$meridianInput = $('body').find('input.bootstrap-timepicker-meridian');173    //$hourInput.autotype('{{back}}{{back}}2');174    //$hourInput.trigger({175      //'type': 'keydown',176      //'keyCode': 9 //tab177    //});178    //expect(tp2.getTime()).toBe('02:30:00 AM');179    //$minuteInput.autotype('{{back}}{{back}}0');180    //$minuteInput.trigger({181      //'type': 'keydown',182      //'keyCode': 9 //tab183    //});184    //expect(tp2.getTime()).toBe('02:00:00 AM');185    //$secondInput.autotype('{{back}}{{back}}30');186    //$secondInput.trigger({187      //'type': 'keydown',188      //'keyCode': 9 //tab189    //});190    //expect(tp2.getTime()).toBe('02:00:30 AM');191    //$meridianInput.autotype('{{back}}{{back}}p');192    //$meridianInput.trigger({193      //'type': 'keydown',194      //'keyCode': 9 //tab195    //});196    //expect(tp2.getTime()).toBe('02:00:30 PM');197  });198  it('should be 12:00 AM if 00:00 AM is entered', function() {199    //$input1.autotype('{{back}}{{back}}{{back}}{{back}}{{back}}{{back}}{{back}}{{back}}0:0 AM');200    //$input1.trigger({201      //'type': 'keydown',202      //'keyCode': 9 //tab203    //});204    //expect(tp1.getTime()).toBe('12:00 AM');205  });206  it('should validate input', function() {207    //var $hourInput = tp1.$widget.find('input.bootstrap-timepicker-hour'),208        //$minuteInput = tp1.$widget.find('input.bootstrap-timepicker-minute'),209        //$meridianInput = tp1.$widget.find('input.bootstrap-timepicker-meridian'),210        //$input3 = tp3.$element;211        //tp1.setTime('11:30 AM');212        //tp1.update();213        //$hourInput.autotype('{{back}}{{back}}13');214        //tp1.updateFromWidgetInputs();215        //expect(tp1.getTime()).toBe('12:30 AM');216        //$minuteInput.autotype('{{back}}{{back}}60');217        //tp1.updateFromWidgetInputs();218        //expect(tp1.getTime()).toBe('12:59 AM');219        //$meridianInput.autotype('{{back}}{{back}}dk');220        //tp1.updateFromWidgetInputs();221        //expect(tp1.getTime()).toBe('12:59 AM');222        //$meridianInput.autotype('{{back}}{{back}}p');223        //tp1.updateFromWidgetInputs();224        //expect(tp1.getTime()).toBe('12:59 PM');225        //$input3.autotype('{{back}}{{back}}{{back}}{{back}}{{back}}{{back}}{{back}}{{back}}25:60:60');226        //tp3.updateFromElementVal();227        //expect(tp3.getTime()).toBe('23:59:59');228  });...

Full Screen

Full Screen

demo.js

Source:demo.js Github

copy

Full Screen

1define(function(require){2	var $ = require("jquery");3	require("cordova!cordova-plugin-ble-central");4	var justep = require("$UI/system/lib/justep");5	var Model = function(){6		this.callParent();7	};8	var utils = require("$UI/demo/plugin/utils");9	var suCallBack = function(info){10		justep.Util.hint("成功:"+JSON.stringify(info));11		console.log(info);12	};13	var errCallBack = function(info){14		justep.Util.hint("失败:"+JSON.stringify(info));15		console.log(info);16	};17	var characteristics;18	var device_id;19	var service_uuid;20	var characteristic_uuid;21	var ble = window.ble;22	var data = new Uint8Array(1);23	data[0] = 1;24	Model.prototype.scanClick = function(event){25		//每发现一个设备就会成功回调一次,会记录最后一个被发现设备的id26		var second = 15;27		alert("扫描"+second+"秒后自动停止扫描")28		ble.scan([],second,function(info){29			suCallBack(info);30			device_id = info.id;31		},errCallBack);32	};33	Model.prototype.startScanClick = function(event){34		////每发现一个设备就会成功回调一次,会记录最后一个被发现设备的id35		ble.startScan([], function(info){36			suCallBack(info);37			device_id = info.id;38		}, errCallBack);39	};40	Model.prototype.stopScanClick = function(event){41		ble.stopScan( suCallBack, errCallBack);42	};43	Model.prototype.connectClick = function(event){44		//连接最后一个被发现的设备45		ble.connect(device_id,  function(info){46			suCallBack(info);47			characteristics  = info.characteristics;48		}, errCallBack);49	};50	Model.prototype.disconnectClick = function(event){51		ble.disconnect(device_id,  suCallBack, errCallBack);52	};53	Model.prototype.readClick = function(event){54		for(var i in characteristics){55			var cha = characteristics[i];56			if (cha.properties[0] == "Read"){57				service_uuid = cha.service;58				characteristic_uuid = cha.characteristic;59				break;60			}61		}62		ble.read(device_id, service_uuid, characteristic_uuid, function(buffer){63			var string = String.fromCharCode.apply(null, new Uint8Array(buffer));64			suCallBack(string);65		}, errCallBack);66	};67	Model.prototype.writeClick = function(event){68		for(var i in characteristics){69			var cha = characteristics[i];70			if (cha.properties[0] == "Write"){71				service_uuid = cha.service;72				characteristic_uuid = cha.characteristic;73				debugger;74				break;75			}76		}77		ble.write(device_id, service_uuid, characteristic_uuid, data.buffer, suCallBack, errCallBack);78	};79	Model.prototype.writeWithoutResponseClick = function(event){80		for(var i in characteristics){81			var cha = characteristics[i];82			if (cha.properties[0] == "Write"){83				service_uuid = cha.service;84				characteristic_uuid = cha.characteristic;85				break;86			}87		}88		ble.writeWithoutResponse(device_id, service_uuid, characteristic_uuid, data.buffer, suCallBack, errCallBack);89	};90	Model.prototype.startNotificationClick = function(event){91		var onData = function(buffer) {92			// Decode the ArrayBuffer into a typed Array based on the data you expect93			var data2 = new Uint8Array(buffer);94			alert("Button state changed to " + data2[0]);95		};96		ble.startNotification(device_id, service_uuid, characteristic_uuid, onData, errCallBack);97	};98	Model.prototype.stopNotificationClick = function(event){99		ble.stopNotification(device_id, service_uuid, characteristic_uuid, suCallBack, errCallBack);100	};101	Model.prototype.isConnectedClick = function(event){102		ble.isConnected(device_id, suCallBack, errCallBack);103	};104	Model.prototype.isEnabledClick = function(event){105		ble.isEnabled(suCallBack, errCallBack);106	};107//	Model.prototype.startStateNotificationsClick = function(event){108//		ble.startStateNotifications(suCallBack, errCallBack);109//	};110//	Model.prototype.stopStateNotificationsClick = function(event){111//		ble.stopStateNotifications(suCallBack, errCallBack);112//	};113	Model.prototype.showBluetoothSettingsClick = function(event){114		ble.showBluetoothSettings(suCallBack, errCallBack);115	};116	Model.prototype.enableClick = function(event){117		ble.enable(suCallBack, errCallBack);118	};119	120	Model.prototype.modelModelConstructDone = function(event){121		utils.showCode(this, "scanClick");122		utils.showCode(this, "startScanClick");123		utils.showCode(this, "stopScanClick");124		utils.showCode(this, "connectClick");125		utils.showCode(this, "disconnectClick");126		utils.showCode(this, "readClick");127		utils.showCode(this, "writeClick");128		utils.showCode(this, "writeWithoutResponseClick");129		utils.showCode(this, "startNotificationClick");130		utils.showCode(this, "stopNotificationClick");131		utils.showCode(this, "isConnectedClick");132		utils.showCode(this, "isEnabledClick");133//		utils.showCode(this, "startStateNotificationsClick");134//		utils.showCode(this, "stopStateNotificationsClick");135		utils.showCode(this, "showBluetoothSettingsClick");136		utils.showCode(this, "enableClick");137		utils.prettyPrint();138	};139	140	return Model;...

Full Screen

Full Screen

mockData.js

Source:mockData.js Github

copy

Full Screen

1export default {2  "1": {3    name: "bulbasaur",4    id: 1,5    species: {6      name: "bulbasaur",7      url: "https://pokeapi.co/api/v2/pokemon-species/1/",8    },9    height: 7,10    weight: 69,11    types: [12      {13        slot: 2,14        type: {15          name: "poison",16          url: "https://pokeapi.co/api/v2/type/4/",17        },18      },19      {20        slot: 1,21        type: {22          name: "grass",23          url: "https://pokeapi.co/api/v2/type/12/",24        },25      },26    ],27    sprites: {28      back_default:29        "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/1.png",30      back_female: null,31      back_shiny:32        "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/1.png",33      back_shiny_female: null,34      front_default:35        "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png",36      front_female: null,37      front_shiny:38        "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/1.png",39      front_shiny_female: null,40    },41  },42  "2": {43    name: "ivysaur",44    id: 2,45    species: {46      name: "ivysaur",47      url: "https://pokeapi.co/api/v2/pokemon-species/2/",48    },49    height: 10,50    types: [51      {52        slot: 2,53        type: {54          name: "poison",55          url: "https://pokeapi.co/api/v2/type/4/",56        },57      },58      {59        slot: 1,60        type: {61          name: "grass",62          url: "https://pokeapi.co/api/v2/type/12/",63        },64      },65    ],66    weight: 130,67    sprites: {68      back_default:69        "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/2.png",70      back_female: null,71      back_shiny:72        "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/2.png",73      back_shiny_female: null,74      front_default:75        "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/2.png",76      front_female: null,77      front_shiny:78        "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/2.png",79      front_shiny_female: null,80    },81  },82  "4": {83    name: "charmander",84    id: 4,85    species: {86      name: "charmander",87      url: "https://pokeapi.co/api/v2/pokemon-species/4/",88    },89    height: 6,90    types: [91      {92        slot: 1,93        type: {94          name: "fire",95          url: "https://pokeapi.co/api/v2/type/10/",96        },97      },98    ],99    weight: 85,100    sprites: {101      back_default:102        "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/4.png",103      back_female: null,104      back_shiny:105        "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/4.png",106      back_shiny_female: null,107      front_default:108        "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/4.png",109      front_female: null,110      front_shiny:111        "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/4.png",112      front_shiny_female: null,113    },114  },115  "7": {116    name: "squirtle",117    id: 7,118    species: {119      name: "squirtle",120      url: "https://pokeapi.co/api/v2/pokemon-species/7/",121    },122    height: 5,123    types: [124      {125        slot: 1,126        type: {127          name: "water",128          url: "https://pokeapi.co/api/v2/type/11/",129        },130      },131    ],132    weight: 90,133    sprites: {134      back_default:135        "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/7.png",136      back_female: null,137      back_shiny:138        "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/7.png",139      back_shiny_female: null,140      front_default:141        "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/7.png",142      front_female: null,143      front_shiny:144        "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/7.png",145      front_shiny_female: null,146    },147  },...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const chromeless = new Chromeless()2  .type('chromeless', 'input[name="q"]')3  .press(13)4  .wait('#resultStats')5  .back()6  .screenshot()7await chromeless.end()8{9  "dependencies": {10  },11  "devDependencies": {12  },13  "scripts": {14  }15}

Full Screen

Using AI Code Generation

copy

Full Screen

1const chromeless = new Chromeless()2  .type('chromeless', 'input[name="q"]')3  .press(13)4  .wait('#resultStats')5  .back()6  .screenshot()7await chromeless.end()8const chromeless = new Chromeless()9  .type('chromeless', 'input[name="q"]')10  .press(13)11  .wait('#resultStats')12  .back()13  .screenshot()14await chromeless.end()15  (Session info: chrome=66.0.3359.181)16  (Driver info: chromedriver=2.42.591059 (4c6d1d8f0f0e9c5d5e5d5b8e0b5f2b5f5f5f5f5f),platform=Windows NT 10.0.16299 x86_64) (WARNING: The server did not provide any stacktrace information)

Full Screen

Using AI Code Generation

copy

Full Screen

1const chromeless = new Chromeless()2async function run() {3        .type('chromeless', 'input[name="q"]')4        .press(13)5        .wait('#resultStats')6        .back()7        .screenshot()8    await chromeless.end()9}10run().catch(console.error.bind(console))11{12  "scripts": {13  },14  "dependencies": {15  }16}

Full Screen

Using AI Code Generation

copy

Full Screen

1const chromeless = new Chromeless();2  .type('chromeless', 'input[name="q"]')3  .press(13)4  .wait('#resultStats')5  .back()6  .screenshot();7await chromeless.end();

Full Screen

Using AI Code Generation

copy

Full Screen

1const chromeless = new Chromeless({ remote: true })2  .type('chromeless', 'input[name="q"]')3  .press(13)4  .wait('#resultStats')5  .back()6  .wait(2000)7  .end()8  .then(() => {9    console.log('done')10  })11const chromeless = new Chromeless({ remote: true })12  .type('chromeless', 'input[name="q"]')13  .press(13)14  .wait('#resultStats')15  .back()16  .wait(2000)17  .end()18  .then(() => {19    console.log('done')20  })21const chromeless = new Chromeless({ remote: true })22  .type('chromeless', 'input[name="q"]')23  .press(13)24  .wait('#resultStats')25  .back()26  .wait(2000)27  .end()28  .then(() => {29    console.log('done')30  })31const chromeless = new Chromeless({ remote: true })32  .type('chromeless', 'input[name="q"]')33  .press(13)34  .wait('#resultStats')35  .back()36  .wait(2000)37  .end()38  .then(() => {39    console.log('done')40  })41const chromeless = new Chromeless({ remote: true })42  .type('chromeless', 'input[name="q"]')43  .press(13)44  .wait('#resultStats')45  .back()46  .wait(2000)47  .end()48  .then(() => {49    console.log('done')50  })51const chromeless = new Chromeless({ remote: true })

Full Screen

Using AI Code Generation

copy

Full Screen

1const chromeless = new Chromeless({ remote: true })2  .type('chromeless', 'input[name="q"]')3  .press(13)4  .wait('#resultStats')5  .back()6  .end()

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run chromeless automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful