Best Karate code snippet using com.intuit.karate.driver.DevToolsMessage
Source:DevToolsDriver.java
...95 // to avoid swamping the console when large base64 encoded binary responses happen96 logger.debug("<< {}", StringUtils.truncate(text, 1024, true));97 }98 Map<String, Object> map = JsonUtils.toJsonDoc(text).read("$");99 DevToolsMessage dtm = new DevToolsMessage(this, map);100 receive(dtm);101 });102 client = new WebSocketClient(wsOptions, logger);103 }104 public int waitSync() {105 if (command == null) {106 return -1;107 }108 return command.waitSync();109 }110 @Override111 public Driver timeout(Integer millis) {112 options.setTimeout(millis);113 return this;114 }115 @Override116 public Driver timeout() {117 return timeout(null);118 }119 public DevToolsMessage method(String method) {120 return new DevToolsMessage(this, method);121 }122 // this can be used for exploring / sending any raw message !123 public Map<String, Object> send(Map<String, Object> map) {124 DevToolsMessage dtm = new DevToolsMessage(this, map);125 dtm.setId(nextId());126 return sendAndWait(dtm, null).toMap();127 }128 public void send(DevToolsMessage dtm) {129 String json = JsonUtils.toJson(dtm.toMap());130 logger.debug(">> {}", json);131 client.send(json);132 }133 public DevToolsMessage sendAndWait(DevToolsMessage dtm, Predicate<DevToolsMessage> condition) {134 boolean wasSubmit = submit;135 if (condition == null && submit) {136 submit = false;137 condition = DevToolsWait.ALL_FRAMES_LOADED;138 }139 //Do stuff inside wait to avoid missing messages140 DevToolsMessage result = wait.send(dtm, condition);141 if (result == null && !wasSubmit) {142 throw new RuntimeException("failed to get reply for: " + dtm);143 }144 return result;145 }146 public void receive(DevToolsMessage dtm) {147 if (dtm.methodIs("Page.domContentEventFired")) {148 domContentEventFired = true;149 logger.trace("** set dom ready flag to true");150 }151 if (dtm.methodIs("Page.javascriptDialogOpening")) {152 currentDialogText = dtm.getParam("message").getAsString();153 // this will stop waiting NOW154 wait.setCondition(DevToolsWait.DIALOG_OPENING);155 }156 if (dtm.methodIs("Page.frameNavigated")) {157 String frameNavId = dtm.get("frame.id", String.class);158 String frameNavUrl = dtm.get("frame.url", String.class);159 if (rootFrameId.equals(frameNavId)) { // root page navigated160 currentUrl = frameNavUrl;161 }162 }163 if (dtm.methodIs("Page.navigatedWithinDocument")) { // js variant of above (SPA, history nav)164 String frameNavId = dtm.get("frameId", String.class);165 String frameNavUrl = dtm.get("url", String.class);166 if (rootFrameId.equals(frameNavId)) { // root page navigated167 currentUrl = frameNavUrl;168 }169 }170 if (dtm.methodIs("Page.frameStartedLoading")) {171 String frameLoadingId = dtm.get("frameId", String.class);172 if (rootFrameId.equals(frameLoadingId)) { // root page is loading173 domContentEventFired = false;174 framesStillLoading.clear();175 frameSessions.clear();176 logger.trace("** root frame started loading, cleared all page state: {}", frameLoadingId);177 } else {178 framesStillLoading.add(frameLoadingId);179 logger.trace("** frame started loading, added to in-progress list: {}", framesStillLoading);180 }181 }182 if (dtm.methodIs("Page.frameStoppedLoading")) {183 String frameLoadedId = dtm.get("frameId", String.class);184 framesStillLoading.remove(frameLoadedId);185 logger.trace("** frame stopped loading: {}, remaining in-progress: {}", frameLoadedId, framesStillLoading);186 }187 if (dtm.methodIs("Target.attachedToTarget")) {188 frameSessions.put(dtm.get("targetInfo.targetId", String.class), dtm.get("sessionId", String.class));189 logger.trace("** added frame session: {}", frameSessions);190 }191 if (dtm.methodIs("Fetch.requestPaused")) {192 handleInterceptedRequest(dtm);193 }194 // all needed state is set above before we get into conditional checks195 wait.receive(dtm);196 }197 private void handleInterceptedRequest(DevToolsMessage dtm) {198 String requestId = dtm.get("requestId", String.class);199 String requestUrl = dtm.get("request.url", String.class);200 if (backend != null) {201 String method = dtm.get("request.method", String.class);202 Map<String, String> headers = dtm.get("request.headers", Map.class);203 String postData = dtm.get("request.postData", String.class);204 logger.debug("intercepting request for url: {}", requestUrl);205 HttpRequest request = new HttpRequest();206 // needed pre-processing for mock feature backend207 StringUtils.Pair pair = NettyUtils.parseUriIntoUrlBaseAndPath(requestUrl);208 request.setUrlBase(pair.left);209 request.setUri(pair.right);210 request.setMethod(method);211 String karateRequestId = System.identityHashCode(dtm) + "";212 MDC.put("karateRequestId", karateRequestId);213 request.setRequestId(karateRequestId);214 headers.forEach((k, v) -> request.addHeader(k, v));215 if (postData != null) {216 request.setBody(FileUtils.toBytes(postData));217 } else {218 request.setBody(FileUtils.EMPTY_BYTES);219 }220 HttpResponse response = backend.buildResponse(request, System.currentTimeMillis());221 String responseBody = response.getBody() == null ? "" : Base64.getEncoder().encodeToString(response.getBody());222 List<Map> responseHeaders = new ArrayList();223 MultiValuedMap mvm = response.getHeaders();224 if (mvm != null) {225 for (String name : mvm.keySet()) {226 Object value = mvm.getFirst(name);227 Map<String, Object> nv = new HashMap(2);228 nv.put("name", name);229 nv.put("value", value);230 responseHeaders.add(nv);231 }232 }233 method("Fetch.fulfillRequest")234 .param("requestId", requestId)235 .param("responseCode", response.getStatus())236 .param("responseHeaders", responseHeaders)237 .param("body", responseBody).sendWithoutWaiting();238 } else {239 logger.warn("no mock server, continuing paused request to url: {}", requestUrl);240 method("Fetch.continueRequest").param("requestId", requestId).sendWithoutWaiting();241 }242 }243 //==========================================================================244 //245 private DevToolsMessage evalOnce(String expression, boolean quickly, boolean fireAndForget) {246 DevToolsMessage toSend = method("Runtime.evaluate")247 .param("expression", expression).param("returnByValue", true);248 if (executionContextId != null) {249 toSend.param("contextId", executionContextId);250 }251 if (quickly) {252 toSend.setTimeout(options.getRetryInterval());253 }254 if (fireAndForget) {255 toSend.sendWithoutWaiting();256 return null;257 }258 return toSend.send();259 }260 protected DevToolsMessage eval(String expression) {261 return eval(expression, false);262 }263 private DevToolsMessage eval(String expression, boolean quickly) {264 DevToolsMessage dtm = evalOnce(expression, quickly, false);265 if (dtm.isResultError()) {266 String message = "js eval failed once:" + expression267 + ", error: " + dtm.getResult().getAsString();268 logger.warn(message);269 options.sleep();270 dtm = evalOnce(expression, quickly, false); // no wait condition for the re-try271 if (dtm.isResultError()) {272 message = "js eval failed twice:" + expression273 + ", error: " + dtm.getResult().getAsString();274 logger.error(message);275 throw new RuntimeException(message);276 }277 }278 return dtm;279 }280 protected void retryIfEnabled(String locator) {281 if (options.isRetryEnabled()) {282 waitFor(locator); // will throw exception if not found283 }284 if (options.highlight) {285 // highlight(locator, options.highlightDuration); // instead of this286 String highlightJs = options.highlight(locator, options.highlightDuration);287 evalOnce(highlightJs, true, true); // do it safely, i.e. fire and forget288 }289 }290 protected int getRootNodeId() {291 return method("DOM.getDocument").param("depth", 0).send().getResult("root.nodeId", Integer.class);292 }293 @Override294 public Integer elementId(String locator) {295 DevToolsMessage dtm = method("DOM.querySelector")296 .param("nodeId", getRootNodeId())297 .param("selector", locator).send();298 if (dtm.isResultError()) {299 return null;300 }301 return dtm.getResult("nodeId").getAsInt();302 }303 @Override304 public List elementIds(String locator) {305 if (locator.startsWith("/")) { // special handling for xpath306 getRootNodeId(); // just so that DOM.getDocument is called else DOM.performSearch fails307 DevToolsMessage dtm = method("DOM.performSearch").param("query", locator).send();308 String searchId = dtm.getResult("searchId", String.class);309 int resultCount = dtm.getResult("resultCount", Integer.class);310 dtm = method("DOM.getSearchResults")311 .param("searchId", searchId)312 .param("fromIndex", 0).param("toIndex", resultCount).send();313 return dtm.getResult("nodeIds", List.class);314 }315 DevToolsMessage dtm = method("DOM.querySelectorAll")316 .param("nodeId", getRootNodeId())317 .param("selector", locator).send();318 if (dtm.isResultError()) {319 return Collections.EMPTY_LIST;320 }321 return dtm.getResult("nodeIds").getAsList();322 }323 @Override324 public DriverOptions getOptions() {325 return options;326 }327 @Override328 public void activate() {329 method("Target.activateTarget").param("targetId", rootFrameId).send();330 }331 protected void initWindowIdAndState() {332 DevToolsMessage dtm = method("Browser.getWindowForTarget").param("targetId", rootFrameId).send();333 if (!dtm.isResultError()) {334 windowId = dtm.getResult("windowId").getValue(Integer.class);335 windowState = (String) dtm.getResult("bounds").getAsMap().get("windowState");336 }337 }338 @Override339 public Map<String, Object> getDimensions() {340 DevToolsMessage dtm = method("Browser.getWindowForTarget").param("targetId", rootFrameId).send();341 Map<String, Object> map = dtm.getResult("bounds").getAsMap();342 Integer x = (Integer) map.remove("left");343 Integer y = (Integer) map.remove("top");344 map.put("x", x);345 map.put("y", y);346 return map;347 }348 @Override349 public void setDimensions(Map<String, Object> map) {350 Integer left = (Integer) map.remove("x");351 Integer top = (Integer) map.remove("y");352 map.put("left", left);353 map.put("top", top);354 Map temp = getDimensions();355 temp.putAll(map);356 temp.remove("windowState");357 method("Browser.setWindowBounds")358 .param("windowId", windowId)359 .param("bounds", temp).send();360 }361 public void emulateDevice(int width, int height, String userAgent) {362 logger.info("Setting deviceMetrics width={}, height={}, userAgent={}", width, height, userAgent);363 method("Network.setUserAgentOverride").param("userAgent", userAgent).send();364 method("Emulation.setDeviceMetricsOverride")365 .param("width", width)366 .param("height", height)367 .param("deviceScaleFactor", 1)368 .param("mobile", true)369 .send();370 }371 @Override372 public void close() {373 method("Page.close").sendWithoutWaiting();374 }375 @Override376 public void quit() {377 if (terminated) {378 return;379 }380 terminated = true;381 // don't wait, may fail and hang382 method("Target.closeTarget").param("targetId", rootFrameId).sendWithoutWaiting();383 // method("Browser.close").send();384 client.close();385 if (command != null) {386 command.close(true);387 }388 }389 @Override390 public boolean isTerminated() {391 return terminated;392 }393 @Override394 public void setUrl(String url) {395 method("Page.navigate").param("url", url)396 .send(DevToolsWait.ALL_FRAMES_LOADED);397 }398 @Override399 public void refresh() {400 method("Page.reload").send(DevToolsWait.ALL_FRAMES_LOADED);401 }402 @Override403 public void reload() {404 method("Page.reload").param("ignoreCache", true).send();405 }406 private void history(int delta) {407 DevToolsMessage dtm = method("Page.getNavigationHistory").send();408 int currentIndex = dtm.getResult("currentIndex").getValue(Integer.class);409 List<Map> list = dtm.getResult("entries").getValue(List.class);410 int targetIndex = currentIndex + delta;411 if (targetIndex < 0 || targetIndex == list.size()) {412 return;413 }414 Map<String, Object> entry = list.get(targetIndex);415 Integer id = (Integer) entry.get("id");416 method("Page.navigateToHistoryEntry").param("entryId", id).send(DevToolsWait.ALL_FRAMES_LOADED);417 }418 @Override419 public void back() {420 history(-1);421 }422 @Override423 public void forward() {424 history(1);425 }426 private void setWindowState(String state) {427 if (!"normal".equals(windowState)) {428 method("Browser.setWindowBounds")429 .param("windowId", windowId)430 .param("bounds", Collections.singletonMap("windowState", "normal"))431 .send();432 windowState = "normal";433 }434 if (!state.equals(windowState)) {435 method("Browser.setWindowBounds")436 .param("windowId", windowId)437 .param("bounds", Collections.singletonMap("windowState", state))438 .send();439 windowState = state;440 }441 }442 @Override443 public void maximize() {444 setWindowState("maximized");445 }446 @Override447 public void minimize() {448 setWindowState("minimized");449 }450 @Override451 public void fullscreen() {452 setWindowState("fullscreen");453 }454 @Override455 public Element click(String locator) {456 retryIfEnabled(locator);457 eval(options.selector(locator) + ".click()");458 return DriverElement.locatorExists(this, locator);459 }460 @Override461 public Element select(String locator, String text) {462 retryIfEnabled(locator);463 eval(options.optionSelector(locator, text));464 return DriverElement.locatorExists(this, locator);465 }466 @Override467 public Element select(String locator, int index) {468 retryIfEnabled(locator);469 eval(options.optionSelector(locator, index));470 return DriverElement.locatorExists(this, locator);471 }472 @Override473 public Driver submit() {474 submit = true;475 return this;476 }477 @Override478 public Element focus(String locator) {479 retryIfEnabled(locator);480 eval(options.focusJs(locator));481 return DriverElement.locatorExists(this, locator);482 }483 @Override484 public Element clear(String locator) {485 eval(options.selector(locator) + ".value = ''");486 return DriverElement.locatorExists(this, locator);487 }488 private void sendKey(char c, int modifiers, String type, Integer keyCode) {489 DevToolsMessage dtm = method("Input.dispatchKeyEvent")490 .param("modifiers", modifiers)491 .param("type", type);492 if (keyCode == null) {493 dtm.param("text", c + "");494 } else {495 switch (keyCode) {496 case 13:497 dtm.param("text", "\r"); // important ! \n does NOT work for chrome498 break;499 case 9: // TAB500 if ("char".equals(type)) {501 return; // special case502 }503 dtm.param("text", "");504 break;505 case 46: // DOT506 if ("rawKeyDown".equals(type)) {507 dtm.param("type", "keyDown"); // special case508 }509 dtm.param("text", ".");510 break;511 default:512 dtm.param("text", c + "");513 }514 dtm.param("windowsVirtualKeyCode", keyCode);515 }516 dtm.send();517 }518 @Override519 public Element input(String locator, String value) {520 retryIfEnabled(locator);521 // focus522 eval(options.focusJs(locator));523 Input input = new Input(value);524 while (input.hasNext()) {525 char c = input.next();526 int modifiers = input.getModifierFlags();527 Integer keyCode = Keys.code(c);528 if (keyCode != null) {529 sendKey(c, modifiers, "rawKeyDown", keyCode);530 sendKey(c, modifiers, "char", keyCode);531 sendKey(c, modifiers, "keyUp", keyCode);532 } else {533 logger.warn("unknown character / key code: {}", c);534 sendKey(c, modifiers, "char", null);535 }536 }537 return DriverElement.locatorExists(this, locator);538 }539 @Override540 public void actions(List<Map<String, Object>> sequence) {541 boolean submitRequested = submit;542 submit = false; // make sure only LAST action is handled as a submit()543 for (Map<String, Object> map : sequence) {544 List<Map<String, Object>> actions = (List) map.get("actions");545 if (actions == null) {546 logger.warn("no actions property found: {}", sequence);547 return;548 }549 Iterator<Map<String, Object>> iterator = actions.iterator();550 while (iterator.hasNext()) {551 Map<String, Object> action = iterator.next();552 String type = (String) action.get("type");553 if (type == null) {554 logger.warn("no type property found: {}", action);555 continue;556 }557 String chromeType;558 switch (type) {559 case "pointerMove":560 chromeType = "mouseMoved";561 break;562 case "pointerDown":563 chromeType = "mousePressed";564 break;565 case "pointerUp":566 chromeType = "mouseReleased";567 break;568 default:569 chromeType = null;570 }571 if (chromeType == null) {572 logger.warn("unexpected action type: {}", action);573 continue;574 }575 Integer x = (Integer) action.get("x");576 Integer y = (Integer) action.get("y");577 if (x != null) {578 currentMouseXpos = x;579 }580 if (y != null) {581 currentMouseYpos = y;582 }583 Integer duration = (Integer) action.get("duration");584 DevToolsMessage toSend = method("Input.dispatchMouseEvent")585 .param("type", chromeType)586 .param("x", currentMouseXpos).param("y", currentMouseYpos);587 if ("mousePressed".equals(chromeType) || "mouseReleased".equals(chromeType)) {588 toSend.param("button", "left").param("clickCount", 1);589 }590 if (!iterator.hasNext() && submitRequested) {591 submit = true;592 }593 toSend.send();594 if (duration != null) {595 options.sleep(duration);596 }597 }598 }599 }600 @Override601 public String text(String id) {602 return property(id, "textContent");603 }604 private <T> T callFunctionOnNode(int nodeId, String function, Class<T> type) {605 DevToolsMessage dtm = method("DOM.resolveNode").param("nodeId", nodeId).send();606 String objectId = dtm.getResult("object.objectId", String.class);607 return callFunctionOnObject(objectId, function, type);608 }609 private <T> T callFunctionOnObject(String objectId, String function, Class<T> type) {610 DevToolsMessage dtm = method("Runtime.callFunctionOn")611 .param("objectId", objectId)612 .param("functionDeclaration", function)613 .send();614 return dtm.getResult().getValue(type);615 }616 @Override617 public String html(String id) {618 return property(id, "outerHTML");619 }620 @Override621 public String value(String locator) {622 return property(locator, "value");623 }624 @Override625 public Element value(String locator, String value) {626 retryIfEnabled(locator);627 eval(options.selector(locator) + ".value = '" + value + "'");628 return DriverElement.locatorExists(this, locator);629 }630 @Override631 public String attribute(String id, String name) {632 retryIfEnabled(id);633 DevToolsMessage dtm = eval(options.selector(id) + ".getAttribute('" + name + "')");634 return dtm.getResult().getAsString();635 }636 @Override637 public String property(String id, String name) {638 retryIfEnabled(id);639 DevToolsMessage dtm = eval(options.selector(id) + "['" + name + "']");640 return dtm.getResult().getAsString();641 }642 @Override643 public boolean enabled(String id) {644 retryIfEnabled(id);645 DevToolsMessage dtm = eval(options.selector(id) + ".disabled");646 return !dtm.getResult().isBooleanTrue();647 }648 @Override649 public boolean waitUntil(String expression) {650 return options.retry(() -> {651 try {652 return eval(expression, true).getResult().isBooleanTrue();653 } catch (Exception e) {654 logger.warn("waitUntil evaluate failed: {}", e.getMessage());655 return false;656 }657 }, b -> b, "waitUntil (js)", true);658 }659 @Override660 public Object script(String expression) {661 return eval(expression).getResult().getValue();662 }663 @Override664 public String getTitle() {665 DevToolsMessage dtm = eval("document.title");666 return dtm.getResult().getAsString();667 }668 @Override669 public String getUrl() {670 return currentUrl;671 }672 @Override673 public List<Map> getCookies() {674 DevToolsMessage dtm = method("Network.getAllCookies").send();675 return dtm.getResult("cookies").getAsList();676 }677 @Override678 public Map<String, Object> cookie(String name) {679 List<Map> list = getCookies();680 if (list == null) {681 return null;682 }683 for (Map<String, Object> map : list) {684 if (map != null && name.equals(map.get("name"))) {685 return map;686 }687 }688 return null;689 }690 @Override691 public void cookie(Map<String, Object> cookie) {692 if (cookie.get("url") == null && cookie.get("domain") == null) {693 cookie = new HashMap(cookie); // don't mutate test694 cookie.put("url", currentUrl);695 }696 method("Network.setCookie").params(cookie).send();697 }698 @Override699 public void deleteCookie(String name) {700 method("Network.deleteCookies").param("name", name).param("url", currentUrl).send();701 }702 @Override703 public void clearCookies() {704 method("Network.clearBrowserCookies").send();705 }706 @Override707 public void dialog(boolean accept) {708 dialog(accept, null);709 }710 @Override711 public void dialog(boolean accept, String text) {712 DevToolsMessage temp = method("Page.handleJavaScriptDialog").param("accept", accept);713 if (text == null) {714 temp.send();715 } else {716 temp.param("promptText", text).send();717 }718 }719 @Override720 public String getDialog() {721 return currentDialogText;722 }723 public byte[] pdf(Map<String, Object> options) {724 DevToolsMessage dtm = method("Page.printToPDF").params(options).send();725 String temp = dtm.getResult("data").getAsString();726 return Base64.getDecoder().decode(temp);727 }728 @Override729 public byte[] screenshot(boolean embed) {730 return screenshot(null, embed);731 }732 @Override733 public Map<String, Object> position(String locator) {734 boolean submitTemp = submit; // in case we are prepping for a submit().mouse(locator).click()735 submit = false;736 retryIfEnabled(locator);737 String expression = options.selector(locator) + ".getBoundingClientRect()";738 // important to not set returnByValue to true739 DevToolsMessage dtm = method("Runtime.evaluate").param("expression", expression).send();740 String objectId = dtm.getResult("objectId").getAsString();741 dtm = method("Runtime.getProperties").param("objectId", objectId).param("accessorPropertiesOnly", true).send();742 submit = submitTemp;743 return options.newMapWithSelectedKeys(dtm.getResult().getAsMap(), "x", "y", "width", "height");744 }745 @Override746 public byte[] screenshot(String id, boolean embed) {747 DevToolsMessage dtm;748 if (id == null) {749 dtm = method("Page.captureScreenshot").send();750 } else {751 Map<String, Object> map = position(id);752 map.put("scale", 1);753 dtm = method("Page.captureScreenshot").param("clip", map).send();754 }755 String temp = dtm.getResult("data").getAsString();756 byte[] bytes = Base64.getDecoder().decode(temp);757 if (embed) {758 options.embedPngImage(bytes);759 }760 return bytes;761 }762 // chrome only763 public byte[] screenshotFull() {764 DevToolsMessage layout = method("Page.getLayoutMetrics").send();765 Map<String, Object> size = layout.getResult("contentSize").getAsMap();766 Map<String, Object> map = options.newMapWithSelectedKeys(size, "height", "width");767 map.put("x", 0);768 map.put("y", 0);769 map.put("scale", 1);770 DevToolsMessage dtm = method("Page.captureScreenshot").param("clip", map).send();771 if (dtm.isResultError()) {772 logger.error("unable to capture screenshot: {}", dtm);773 return new byte[0];774 }775 String temp = dtm.getResult("data").getAsString();776 return Base64.getDecoder().decode(temp);777 }778 @Override779 public List<String> getPages() {780 DevToolsMessage dtm = method("Target.getTargets").send();781 return dtm.getResult("targetInfos.targetId").getAsList();782 }783 @Override784 public void switchPage(String titleOrUrl) {785 if (titleOrUrl == null) {786 return;787 }788 DevToolsMessage dtm = method("Target.getTargets").send();789 List<Map> targets = dtm.getResult("targetInfos").getAsList();790 String targetId = null;791 String targetUrl = null;792 for (Map map : targets) {793 String title = (String) map.get("title");794 String url = (String) map.get("url");795 if ((title != null && title.contains(titleOrUrl))796 || (url != null && url.contains(titleOrUrl))) {797 targetId = (String) map.get("targetId");798 targetUrl = url;799 break;800 }801 }802 if (targetId != null) {803 method("Target.activateTarget").param("targetId", targetId).send();804 currentUrl = targetUrl;805 } else {806 logger.warn("failed to switch page to {}", titleOrUrl);807 }808 }809 @Override810 public void switchPage(int index) {811 if (index == -1) {812 return;813 }814 DevToolsMessage dtm = method("Target.getTargets").send();815 List<Map> targets = dtm.getResult("targetInfos").getAsList();816 if (index < targets.size()) {817 Map target = targets.get(index);818 String targetId = (String) target.get("targetId");819 method("Target.activateTarget").param("targetId", targetId).send();820 currentUrl = (String) target.get("url");821 } else {822 logger.warn("failed to switch frame by index: {}", index);823 }824 }825 @Override826 public void switchFrame(int index) {827 if (index == -1) {828 executionContextId = null;829 sessionId = null;830 return;831 }832 List<Integer> ids = elementIds("iframe,frame");833 if (index < ids.size()) {834 Integer nodeId = ids.get(index);835 setExecutionContext(nodeId, index);836 } else {837 logger.warn("unable to switch frame by index: {}", index);838 }839 }840 @Override841 public void switchFrame(String locator) {842 if (locator == null) {843 executionContextId = null;844 sessionId = null;845 return;846 }847 retryIfEnabled(locator);848 Integer nodeId = elementId(locator);849 if (nodeId == null) {850 return;851 }852 setExecutionContext(nodeId, locator);853 }854 private void setExecutionContext(int nodeId, Object locator) {855 DevToolsMessage dtm = method("DOM.describeNode")856 .param("nodeId", nodeId)857 .param("depth", 0)858 .send();859 String frameId = dtm.getResult("node.frameId", String.class);860 if (frameId == null) {861 logger.warn("unable to find frame by nodeId: {}", locator);862 return;863 }864 sessionId = frameSessions.get(frameId);865 if (sessionId != null) {866 logger.trace("found out-of-process frame - session: {} - {}", frameId, sessionId);867 return;868 }869 dtm = method("Page.createIsolatedWorld").param("frameId", frameId).send();...
Source:Chrome.java
...36import com.intuit.karate.core.ScenarioEngine;37import com.intuit.karate.core.ScenarioRuntime;38import com.intuit.karate.core.Variable;39import com.intuit.karate.driver.DevToolsDriver;40import com.intuit.karate.driver.DevToolsMessage;41import com.intuit.karate.driver.Driver;42import com.intuit.karate.driver.DriverOptions;43import com.intuit.karate.driver.Input;44import com.intuit.karate.driver.Keys;45import com.intuit.karate.http.Response;46import com.intuit.karate.shell.Command;47import asura.ui.driver.DriverProvider;48import asura.ui.karate.KarateRunner;49/**50 * @author pthomas351 */52public class Chrome extends DevToolsDriver {53 private static Logger logger = LoggerFactory.getLogger(Chrome.class);54 public static final String DEFAULT_PATH_MAC = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";55 public static final String DEFAULT_PATH_WIN = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";56 public static final String DEFAULT_PATH_LINUX = "/usr/bin/google-chrome";57 public Driver parent; // used in 'DriverPoolActor'58 public ScenarioEngine engine;59 public Boolean inject;60 public Consumer<Map<String, Object>> filter;61 public Chrome(DriverOptions options, Command command, String webSocketUrl) {62 super(options, command, webSocketUrl);63 }64 // èªå®ä¹65 public Chrome(DriverOptions options, Command command, String webSocketUrl,66 ScenarioEngine engine, Boolean inject, Consumer<Map<String, Object>> filter67 ) {68 super(options, command, webSocketUrl);69 this.engine = engine;70 this.inject = inject;71 this.filter = filter;72 if (this.inject && this.engine != null) {73 this.engine.setDriver(this);74 }75 client.setTextHandler(text -> {76 Map<String, Object> map = Json.of(text).value();77 DevToolsMessage dtm = new DevToolsMessage(this, map);78 if (this.filter != null && !StringUtils.isBlank(dtm.getMethod())) {79 this.filter.accept(map);80 }81 receive(dtm);82 return false; // no async signalling, for normal use, e.g. chrome developer tools83 });84 }85 public void closeClient() {86 client.close();87 }88 public void enableLog() {89 method("Log.enable").send();90 }91 public void enableDom() {92 method("DOM.enable").send();93 }94 public void setDiscoverTargets() {95 method("Target.setDiscoverTargets").param("discover", true).send();96 }97 public String screenshotAsBase64() {98 Variable result = method("Page.captureScreenshot").send().getResult("data");99 if (result != null) {100 return result.getAsString();101 } else {102 return null;103 }104 }105 public DevToolsMessage openNewPage(String url) {106 return method("Target.createTarget")107 .param("url", url)108 .param("newWindow", false)109 .param("background", true)110 .send();111 }112 public List<Map<String, Object>> getJsonPageTargets() {113 Http http = options.getHttp();114 Command.waitForHttp(http.urlBase + "/json");115 Response res = http.path("json").get();116 List<Map<String, Object>> targets = res.json().asList();117 return targets;118 }119 public void goToTop(Integer idx) {120 List<Map<String, Object>> targets = getJsonPageTargets();121 if (targets.size() > idx) {122 Map<String, Object> target = targets.get(idx);123 reconnect((String) target.get("webSocketDebuggerUrl"));124 } else {125 throw new RuntimeException("only " + targets.size() + " pages.");126 }127 }128 public void switchPage2(String urlOrTitle) {129 if (urlOrTitle.matches("-?(0|[1-9]\\d*)")) { // nums130 goToTop(Integer.parseInt(urlOrTitle));131 } else {132 List<Map<String, Object>> targets = getJsonPageTargets();133 for (Map target : targets) {134 String targetUrl = (String) target.get("url");135 String targetTitle = (String) target.get("title");136 if (targetUrl.contains(urlOrTitle) || targetTitle.contains(urlOrTitle)) {137 reconnect((String) target.get("webSocketDebuggerUrl"));138 break;139 }140 }141 }142 }143 public void closeOthers() {144 DevToolsMessage dtm = method("Target.getTargets").send();145 List<Map> targets = dtm.getResult("targetInfos").getValue();146 if (targets != null) {147 targets.forEach(target -> {148 if ("page".equals(target.get("type"))) {149 String targetId = target.getOrDefault("targetId", "").toString();150 if (!rootFrameId.equals(targetId)) {151 method("Target.closeTarget").param("targetId", targetId).sendWithoutWaiting();152 }153 }154 });155 }156 }157 public void sendKey(char c, int modifiers, String type, Integer keyCode) {158 DevToolsMessage dtm = method("Input.dispatchKeyEvent")159 .param("modifiers", modifiers)160 .param("type", type);161 if (keyCode == null) {162 dtm.param("text", c + "");163 } else {164 switch (keyCode) {165 case 13:166 dtm.param("text", "\r"); // important ! \n does NOT work for chrome167 break;168 case 9: // TAB169 if ("char".equals(type)) {170 return; // special case171 }172 dtm.param("text", "");...
DevToolsMessage
Using AI Code Generation
1import com.intuit.karate.driver.DevToolsMessage;2import java.util.HashMap;3import java.util.Map;4public class 4 {5 public static void main(String[] args) throws Exception {6 Map<String, Object> params = new HashMap();7 DevToolsMessage message = new DevToolsMessage("Page.navigate", params);8 System.out.println(message.getJson());9 System.out.println(message2.getJson());10 }11}12import com.intuit.karate.driver.DevToolsMessage;13import java.util.HashMap;14import java.util.Map;15public class 5 {16 public static void main(String[] args) throws Exception {17 Map<String, Object> params = new HashMap();18 DevToolsMessage message = new DevToolsMessage("Page.navigate", params);19 System.out.println(message.getJson());20 System.out.println(message2.getJson());21 }22}23import com.intuit.karate.driver.DevToolsMessage;24import java.util.HashMap;25import java.util.Map;26public class 6 {27 public static void main(String[] args) throws Exception {28 Map<String, Object> params = new HashMap();29 DevToolsMessage message = new DevToolsMessage("Page.navigate", params);30 System.out.println(message.getJson());31 System.out.println(message2.getJson());32 }33}34import com.intuit.karate.driver.DevToolsMessage;35import java.util.HashMap;36import java.util.Map;37public class 7 {38 public static void main(String[] args) throws Exception {
DevToolsMessage
Using AI Code Generation
1import com.intuit.karate.driver.DevToolsMessage2import com.intuit.karate.driver.DevToolsDriver3import com.intuit.karate.driver.DevToolsDriverFactory4import com.intuit.karate.driver.DevToolsDriverOptions5import com.intuit.karate.driver.DevToolsDriverOptionsBuilder6import org.openqa.selenium.chrome.ChromeDriver7import org.openqa.selenium.chrome.ChromeOptions8import org.openqa.selenium.chrome.ChromeDriverService9import org.openqa.selenium.chrome.ChromeOptions10import org.openqa.selenium.remote.DesiredCapabilities11import java.io.File12import java.net.URL13import org.openqa.selenium.chrome.ChromeDriverService14import org.openqa.selenium.chrome.ChromeOptions15import org.openqa.selenium.remote.DesiredCapabilities16import java.io.File17import java.net.URL18import org.openqa.selenium.chrome.ChromeDriverService19import org.openqa.selenium.chrome.ChromeOptions20import org.openqa.selenium.remote.DesiredCapabilities21import java.io.File22import java.net.URL23import org.openqa.selenium.chrome.ChromeDriverService24import org.openqa.selenium.chrome.ChromeOptions25import org.openqa.selenium.remote.DesiredCapabilities26import java.io.File27import java.net.URL
DevToolsMessage
Using AI Code Generation
1import com.intuit.karate.driver.DevToolsMessage2import com.intuit.karate.driver.DevToolsMessage.*3import com.intuit.karate.driver.DevToolsMessage.MessageType.*4def message = DevToolsMessage.of(REQUEST, 'Network.enable')5logger.info message.toString()6import com.intuit.karate.driver.DevToolsMessage7import com.intuit.karate.driver.DevToolsMessage.*8import com.intuit.karate.driver.DevToolsMessage.MessageType.*9def message = DevToolsMessage.of(RESPONSE, 'Network.enable')10logger.info message.toString()11import com.intuit.karate.driver.DevToolsMessage12import com.intuit.karate.driver.DevToolsMessage.*13import com.intuit.karate.driver.DevToolsMessage.MessageType.*14def message = DevToolsMessage.of(EVENT, 'Network.enable')15logger.info message.toString()16import com.intuit.karate.driver.DevToolsMessage17import com.intuit.karate.driver.DevToolsMessage.*18import com.intuit.karate.driver.DevToolsMessage.MessageType.*19def message = DevToolsMessage.of(NOTIFICATION, 'Network.enable')20logger.info message.toString()21import com.intuit.karate.driver.DevToolsMessage22import com.intuit.karate.driver.DevToolsMessage.*23import com.intuit.karate.driver.DevToolsMessage.MessageType.*24def message = DevToolsMessage.of(REQUEST, 'Network.enable')25message.setParam('foo', 'bar')26logger.info message.toString()27import com.intuit.karate.driver.DevToolsMessage28import com.intuit.karate.driver.DevToolsMessage.*29import com.intuit.karate.driver.DevToolsMessage.MessageType.*30def message = DevToolsMessage.of(REQUEST, 'Network.enable')31message.setParam('foo', 'bar')32logger.info message.getParam('foo')
DevToolsMessage
Using AI Code Generation
1import com.intuit.karate.driver.DevToolsMessage;2import com.intuit.karate.driver.DevTools;3DevToolsMessage message = new DevToolsMessage();4message.setMethod("Runtime.evaluate");5message.setParams("{\"expression\":\"document.getElementById('lst-ib').value='Hello World'\"}");6DevTools devTools = new DevTools();7devTools.connect();8DevToolsMessage response = devTools.send(message);9System.out.println(response.toJson());10devTools.disconnect();11import com.intuit.karate.driver.DevToolsMessage;12import com.intuit.karate.driver.DevTools;13DevToolsMessage message = new DevToolsMessage();14message.setMethod("Runtime.evaluate");15message.setParams("{\"expression\":\"document.getElementById('lst-ib').value='Hello World'\"}");16DevTools devTools = new DevTools();17devTools.connect();18DevToolsMessage response = devTools.send(message);19System.out.println(response.toJson());20devTools.disconnect();21import com.intuit.karate.driver.DevToolsMessage;22import com.intuit.karate.driver.DevTools;23DevToolsMessage message = new DevToolsMessage();24message.setMethod("Runtime.evaluate");25message.setParams("{\"expression\":\"document.getElementById('lst-ib').value='Hello World'\"}");26DevTools devTools = new DevTools();27devTools.connect();28DevToolsMessage response = devTools.send(message);29System.out.println(response.toJson());30devTools.disconnect();
DevToolsMessage
Using AI Code Generation
1import com.intuit.karate.driver.DevToolsMessage;2import com.intuit.karate.driver.DevToolsService;3import com.intuit.karate.driver.chrome.ChromeDevToolsService;4import java.util.Map;5public class 4 {6 public static void main(String[] args) {7 DevToolsService service = new ChromeDevToolsService();8 DevToolsMessage message = service.send("Page.enable", null);9 Map<String, Object> result = message.getResult();10 System.out.println(result);11 }12}
DevToolsMessage
Using AI Code Generation
1import com.intuit.karate.driver.DevToolsMessage;2message.send();3import com.intuit.karate.driver.DevToolsMessage;4message.send();5import com.intuit.karate.driver.DevToolsMessage;6message.send();7import com.intuit.karate.driver.DevToolsMessage;8message.send();9import com.intuit.karate.driver.DevToolsMessage;10message.send();11import com.intuit.karate.driver.DevToolsMessage;12message.send();13import com.intuit.karate.driver.DevToolsMessage;14message.send();
DevToolsMessage
Using AI Code Generation
1package demo;2import com.intuit.karate.driver.DevToolsMessage;3import com.intuit.karate.driver.DevToolsService;4import com.intuit.karate.driver.chrome.ChromeDriver;5import com.intuit.karate.driver.chrome.ChromeService;6import com.intuit.karate.driver.chrome.ChromeSession;7import com.intuit.karate.driver.chrome.ChromeTab;8import com.intuit.karate.driver.chrome.ChromeTabId;9import com.intuit.karate.driver.chrome.ChromeTarget;10import com.intuit.karate.driver.chrome.ChromeVersion;11import java.util.List;12import org.openqa.selenium.chrome.ChromeOptions;13public class Demo {14 public static void main(String[] args) {15 ChromeService service = ChromeService.start();16 ChromeDriver driver = new ChromeDriver(service);17 ChromeOptions options = new ChromeOptions();18 options.addArguments("--headless");19 ChromeSession session = driver.createSession(options);20 List<ChromeTarget> targets = session.getTargets();21 for (ChromeTarget target : targets) {22 if (target.getType().equals("page")) {23 ChromeTab tab = session.attach(target);24 ChromeTabId tabId = tab.getTabId();25 DevToolsService devToolsService = tab.getDevToolsService();26 DevToolsMessage message = new DevToolsMessage("Network.enable");27 devToolsService.sendMessage(message, tabId);28 message = new DevToolsMessage("Performance.enable");29 devToolsService.sendMessage(message, tabId);30 message = new DevToolsMessage("Performance.start");31 devToolsService.sendMessage(message, tabId);32 message = new DevToolsMessage("Performance.stop");33 devToolsService.sendMessage(message, tabId);34 message = new DevToolsMessage("Performance.getMetrics");35 devToolsService.sendMessage(message, tabId);36 message = new DevToolsMessage("Network.getResponseBody", "{\"requestId\":\"b8d7b1a9-9c1d-4d0f-8e8b-3d3e7f8f5f1b\"}");37 devToolsService.sendMessage(message, tabId);38 message = new DevToolsMessage("Network.getResponseBody", "{\"requestId\":\"a0b8d7b1a9-9c1d-4d
DevToolsMessage
Using AI Code Generation
1import com.intuit.karate.driver.DevToolsMessage;2import java.io.IOException;3import java.net.URISyntaxException;4import java.util.HashMap;5import java.util.Map;6public class 4 {7 public static void main(String[] args) throws IOException, URISyntaxException {8 Map<String, Object> map = new HashMap<>();9 map.put("foo", "bar");10 DevToolsMessage message = new DevToolsMessage("myMessage", map);11 }12}13import com.intuit.karate.driver.DevToolsMessage;14import java.io.IOException;15import java.net.URISyntaxException;16import java.util.HashMap;17import java.util.Map;18public class 5 {19 public static void main(String[] args) throws IOException, URISyntaxException {20 Map<String, Object> map = new HashMap<>();21 map.put("foo", "bar");22 DevToolsMessage message = new DevToolsMessage("myMessage", map);23 }24}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!