Why isn't the login redirect script working without any errors or redirection?

Struggling to develop a Greasemonkey script that can automatically fill in certain forms and then redirect to another URL once the form is submitted.

// ==UserScript==
// @name     usersaime
// @description fills data form for user and pass 
// @include https://tramites.saime.gob.ve/*
// @version  1.1
// @grant    none
// ==/UserScript==
document.getElementById('LoginForm_username').value = "user";
document.getElementById('LoginForm_password').value = "1234";

setTimeout(function() {
    document.getElementById('login_button').click();
}, 2000);

window.addEventListener('load', function(event) {
    // all resources finished loading
    window.location = 'https://tramites.saime.gob.ve/index/example/example';
});

Despite attempting various methods such as window.location.href and window.location.replace, as well as using a setTimeout function, I am unable to get the window.location to work properly.

No errors are showing in the console.

Tested on:

  • Firefox 59 with Greasemonkey 4.3
  • Chrome 66 with Tampermonkey 4.5

The login page/form URL is

https://tramites.saime.gob.ve/index.php?r=site/login
.
Upon successful login, it redirects to
https://tramites.saime.gob.ve/index.php?r=tramite/tramite/
, which is where I want the redirection to occur.

Answer №1

Here is a straightforward explanation:
The reason why window.location may not be working for you is:

  1. The call to window.location is placed within a window's load event handler.
  2. The target page triggers the load event almost immediately after the DOMContentLoaded event.
  3. Normally, userscripts execute at DOMContentLoaded, but in this case, the load event has already been triggered when your script runs.

The actual issue:
There are several problems with the code in question:

  1. It does not take into account and address the different states of the process. The script needs to behave differently based on the state it encounters on various pages.
  2. The page(s) heavily rely on AJAX operations, which the code fails to handle appropriately.
  3. In this scenario, the load event does not provide significant help.
  4. There exists a timing conflict between script execution and the load event.
  5. Including login credentials directly in the script poses a severe security risk and makes it susceptible to exploitation.

To resolve these issues, you need to differentiate between at least 3 distinct states by utilizing information such as the URLs of pages, key elements on the pages, or stored/passed state variables within the script.

The following userscript demonstrates the process, although testing may be restricted due to authentication requirements, as discussed in this related thread:

// ==UserScript==
// @name     _Login and then redirect an AJAX-driven page
// @include  https://tramites.saime.gob.ve/*
// @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// @grant    GM.getValue
// ==/UserScript==
//- The @grant directives ensure proper handling.

//--- Different actions needed for different pages
if (location.search.includes ("site/login") ) {  
    //-- Wait for page setup completion
    waitForKeyElements ("#login_button:visible", loginWhenReady);
}
else if (location.search.includes ("tramite/tramite") ) {  
    //-- Simply redirect
    location.assign ("https://tramites.saime.gob.ve/index/example/example");
}
else {
    //-- No action required on other pages.
}

function loginWhenReady (jNode) {
    //-- For demonstration purposes only - Usage of framework or password manager recommended!
    $("#LoginForm_username").val ("user");
    $("#LoginForm_password").val ("1234");

    clickNode (jNode); 
}
function clickNode (jNode) {
    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    jNode[0].dispatchEvent (clickEvent);
}


Possible efficient resolution:

  1. If-and-only-if (IIF) the post login page always ends in
    https://tramites.saime.gob.ve/index.php?r=tramite/tramite/
    .
  2. AND IIF that specific page serves no other relevant purpose...

Then the following userscript might meet your requirements effectively:

// ==UserScript==
// @name     _Quick and dirty post login redirect
// @include  https://tramites.saime.gob.ve/index.php?r=tramite/tramite*
// @grant    none
// @run-at   document-start
// ==/UserScript==

location.replace ("https://tramites.saime.gob.ve/index/example/example");

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

To collapse a div in an HTML Angular environment, the button must be clicked twice

A series of divs in my code are currently grouped together with expand and collapse functionality. It works well, except for the fact that I have to click a button twice in order to open another div. Initially, the first click only collapses the first div. ...

Which Client-Side JavaScript Frameworks Pair Seamlessly With Node.js, Express.js, and socket.io.js?

Currently, I am in the process of developing a web application utilizing Node.js, Express.js, and socket.io.js on the server side. Are there any front-end frameworks (such as Agility, Angular, Backbone, Closure, Dojo, Ember, GWT, jQuery, Knockback, Knocko ...

The Chrome debugger will pause execution at a function without needing a DOM break point

Greetings! I am currently working on an angular js application. One issue that I have encountered is when I run the application and open the debugger by hitting F12, I notice that for every page it continuously calls a certain function and seems to stop th ...

Dealing with redirect issues in a React-Material menu: A guide to troubleshooting and

When working with my menu, I face a variety of issues. First and foremost, within the initial RETURN section, there is a TREEITEM with a LISTITEM and a LISTITETEXT. I have included an OnClick event in the LISTITETEXT so that if the menu's id matches ...

The form within the dynamically loaded AJAX content is malfunctioning

My webpage is set up to load content from a separate file (content.php) into a div and refresh it every 5 seconds. In the content.php file, I have a form (basic HTML without javascript) that works fine when accessed directly at (example.com/content.php). ...

The versatility of reusable Backbone components

As I search for the best way to ensure the reusability of Backbone views, I have come across various solutions but am unsure which one would best meet my needs. My goal is to create multiple widgets populated with real-time data and I require a base compon ...

What is the object pattern in Typescript?

Recently delving into TypeScript, I am eager to learn how to define an interface for the following type of object: const branch = { 'CN': { 'name': 'CN Name', 'branch': 'Chinoise', 'url& ...

How can I efficiently display three items per click when tapping into jQuery data?

Here is the code that I have been working on: jQuery(document).ready(function( $ ) { var $container = $('#homegrid').masonry({ isAnimated: true, itemSelector: '.home-blocks', columnWidth: '.grid-sizer ...

The sinuous waveform in JavaScript

track : function(x, y, top, ampl) { return { top : top + 2, x : x + ampl * Math.sin(top / 20), y : (top / this.screenHeight < 0.65) ? y + 2 : 1 + y + ampl * Math.cos(top / 25) }; } This specif ...

Refresh the Vuex store using the main process of Electron

Is there a way to update a vuex store by committing changes from the main process? Here is an example: In the main thread: import store from '../store' ipc.on('someevent', (event, args) => { // do something with args store ...

`Is there a way to sort a deeply nested object by its values?`

I need assistance sorting an array of hospitals based on the lowest value of the amountinINR key, especially when dealing with deeply nested arrays of hospital objects. Does anyone know how to achieve this without using third-party libraries like lodash or ...

`Switching the selection in ng-selected`

I am having trouble toggling ng-selected options in Angular. I have tried the following approach: <select ng-model="datacut.ages" multiple> <option value="" disabled="disabled">Please Select</option> <option value="0-15" ng-clic ...

Unable to execute Javascript function within a click event handler

I am encountering an issue with a div that is loaded through ajax. Here is the structure of the div: <div id="container"> <a href="#" class="easyui-linkbutton submit_data">Click here to submit</a> </div> Within the same file c ...

The peculiar characteristics of the dragLeave event in various web browsers

I observed a peculiar behavior while working with drag events in Internet Explorer 11. It seems that adding a 'width' property to the elements triggers the dragLeave event, whereas without it, the event does not fire. Can anyone shed light on why ...

Retrieve the initial value from the TextField

My website features multiple filters, including by date and duration, allowing users to easily find the information they need from a large dataset. There is also a "reset all filters" button that clears all filters and displays the full list of products. ...

Having difficulty receiving a response from an AJAX call within the success function

After browsing through this stack link Ajax response not calling success:function() when using jQuery 1.8.3, I'm puzzled as to why the success function is not invoked when I uncomment the dataType line. It seems that setting dataType = JSON prevents t ...

Is it possible to display a Processing message at the beginning of a datatables table already containing data?

Within my Laravel 5.7 application, I have implemented the "yajra/laravel-datatables-oracle": "~8.0" library and found a helpful thread on customizing the processing message at this link. I adjusted the processing message styling as follows: .dataTables_pr ...

Complete and automatically submit a form in a view using AngularJS

I have developed a basic AngularJS application that is functioning smoothly. Currently, I am looking to populate certain fields and submit the form directly from the view without requiring any user input. Below, you'll find some simplified JavaScrip ...

Exploring the Function Scope within ViewModel

I have been facing an issue while trying to call a function from my ViewModel within a foreach loop. It seems like the function goes out of scope as soon as I call it. Being new to JavaScript, I am struggling to understand why this is happening. Here is t ...

Is it possible to decode a two-dimensional array of objects in JSON?

My scenario involves a two-dimensional array of objects structured as follows: function test(n){ this.id = n; } var testArray= new Array(2); for(i = 0; i < testArray.length; i++){ testArray[i] = new Array(2); for(j = 0; j < testArray[i].lengt ...