Looking to halt navigation in a Chrome browser immediately after performing a click action with Selenium?

Is there a way to prevent the browser from loading immediately after a click event? Are there any workarounds or JavaScript implementations for achieving this?

Answer №1

To implement a delay in your click action, you can utilize javascript's setTimeout and setInterval.

<a onclick="delayLoader()">Click</a>

function delayLoader(){
    setTimeout(function(){      
        window.location = 'https://www.example.com';
    }, 3000);
}

Answer №2

An easy workaround that comes to mind is redirecting to a 'fake page' immediately after clicking. For example, . Alternatively, if this method doesn't suit your needs, you can try using the equivalent of sendkeys in JavaScript to simulate pressing the 'ESC' key, which will stop page loading in Chrome.

In Java:

public Keys soloKey(int key) throws AWTException  
{
      Robot r;
        try 
        {
             r = new Robot();
             r.keyPress(key);
             r.keyRelease(key); 
        }
            catch (AWTException e) {
            e.printStackTrace();}
        return null;
}

soloKey(KeyEvent.VK_ESCAPE);

In Javascript:

var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";


keyboardEvent[initMethod](
                   "keydown", // event type : keydown, keyup, keypress
                    true, // bubbles
                    true, // cancelable
                    window, // viewArg: should be window
                    false, // ctrlKeyArg
                    false, // altKeyArg
                    false, // shiftKeyArg
                    false, // metaKeyArg
                    27, // keyCodeArg : unsigned long the virtual key code, else 0
                    0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
document.dispatchEvent(keyboardEvent);

The idea for the JavaScript solution was borrowed from: js-press-key

Here is a reference for keyCodes (27 corresponds to ESC) js-key-codes

I hope this information proves useful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JSON with Google Chart Tools

When referring to this example at , it is noted that the method data.addRows() requires a list of lists. A URI (/data/mydata.json) can be accessed to retrieve the following data: [["Canada", 66], ["Turkey", 10], ["Hungary", 23], ["Italy", 49]] Despite a ...

Assigning attributes to each letter in a pangram

I am attempting to assign the appropriate class to a group of elements, representing each letter in the alphabet. The elements have IDs ranging from #alpha_0 to #alpha_25. If a letter appears just once in the input, it should be displayed in green. If a le ...

Whenever I add a new Task in React.js, the date is not visible to me

I'm currently deepening my understanding of React, and I've encountered a roadblock. The issue arises when I attempt to create a Tracking Task - the task is successfully created from the form inputs but the date associated with the new task isn&a ...

Saving JavaScript variables to a JSON file

In my possession is a JSON file named example_json.json, which contains the following data: { "timeline": { "headline":"WELCOME", "type":"default", "text":"People say stuff", "startDate":"10/4/2011 15:02:00", ...

Matching an element that contains a specific string in JS/CSS

I'm currently faced with an HTML file that's being generated by an outdated system, making it tricky for me to control the code generation process. The structure of the HTML code is as follows: <table cellpadding=10> <tr> ...

Displaying Real-Time Values in ReactJS

Hi there, I am currently using the code below to upload images to Cloudinary: import React, { Component } from 'react'; import './App.css'; import Dropzone from 'react-dropzone'; import axios from 'axios'; const F ...

selenium.common.exceptions.WebDriverException: Message: Required capabilities need to be specified as a dictionary in PYTHON 3

Hello, I encountered the following error: Traceback (most recent call last): File "C:\Users\Gebruiker\Desktop\email-account-generator-master\EmailAccountGenerator.py", line 40, in <module> driver = webdriver.Remote(ser ...

Why do we include 'By' in the method parameters?

I am wondering about the functionality of using "By" as an argument in the method provided below. Can someone shed some light on its purpose? public boolean click(By by, String...elementName) { try { getElement(by).click(); if(elemen ...

The error callback encountered {"readyState":4,"status":200,"statusText":"success"} while processing

When I make a call to this url, the response is a JSON object when done directly in the browser. However, when I try to do it via ajax using the following code snippet: $.ajax({ url: url, type: "GET", dataType:"jsonp", succ ...

Unable to fetch a new session from the selenium server due to an error

I'm currently in the process of setting up Nightwatch.js for the very first time. I am following the tutorial provided at this link: https://github.com/dwyl/learn-nightwatch Unfortunately, I have encountered a barrier and require assistance to resolv ...

Having trouble with the Tap to copy discount code function not working in the Shopify cart drawer?

Our goal is to implement tap to copy functionality for code snippets on our Shopify website. It works seamlessly on the product detail page, but in the cart drawer, it only functions properly after the second page load. {% if cart.total_price > 0 % ...

Effectively encoding and decoding AJAX and JSON objects with PHP scripting

I've successfully set up a basic HTML file with a fixed JSON object. My goal is to transfer this object to a PHP file named text.php, encode it, decode it, display it in the PHP file, and then showcase it back in the HTML file. <!DOCTYPE html> ...

There are three pop-up windows displayed on the screen. When each one is clicked, they open as intended, but the information inside does not

Every button triggers a unique modal window Encountering an unusual problem with Bootstrap 5 modal functionality. Within a webpage displaying a list of database entries (refer to the screenshot), each entry features three buttons to open corresponding mod ...

What are the steps to integrate Webpack into an EJS Reactjs Express MongoDb application?

I have incorporated EJS, Express/NodeJs, and MongoDB into the project, along with ReactJs as an addition. My next step is to introduce Webpack for bundling both EJS and ReactJs files together. Although the end goal is to transition the p ...

Guide on parsing and totaling a string of numbers separated by commas

I am facing an issue with reading data from a JSON file. Here is the code snippet from my controller: myApp.controller("abcdctrl", ['$scope', 'orderByFilter', '$http', function ($scope, orderBy, $http) { console.log('abc ...

Can you explain the slow parameter feature in Mocha?

While configuring mochaOpts in Protractor, one of the parameters we define is 'slow'. I'm unsure of the purpose of this parameter. I attempted adjusting its value but did not observe any impact on the test execution time. mochaOpts: { re ...

Revert animation back to its initial position with the help of JavaScript

After implementing the script below, I successfully managed to shift my image to the right upon clicking: <script> var myTimer = null; function move(){ document.getElementById("fish").style.left = parseInt(document.getElementById("fish ...

Tips for implementing if/else condition with onclick feature in Selenium Webdriver

How can I implement if/else conditions in Selenium WebDriver using Java? I need each step to be clicked and executed once it has been selected. The condition of Number_Select.NumberRandom(driver, 2).click(); should correspond to selection 2 in the if-else ...

How can one overcome CORS policies to retrieve the title of a webpage using JavaScript?

As I work on a plugin for Obsidian that expands shortened urls like bit.ly or t.co to their full-length versions in Markdown, I encounter a problem. I need to fetch the page title in order to properly create a Markdown link [title](web link). Unfortunatel ...

The ui.bootstrap.carousel component seems to be missing from the display

My Carousel is not displaying for some unknown reason. I have customized the implementation based on my project requirements which differ slightly from the standard guidelines. Despite this, it should function correctly as detailed below. By clicking on m ...