Explore various query strings without the risk of JavaScript overwriting references to previous variables

Seeking to extract data from this specific website, I've developed a javascript function that effectively retrieves the necessary information:

const total_planning_applications = 39437
const min_value = 39407
var superArray = []
var i = 1
window.location.href = "http://www2.ashfield.gov.uk/cfusion/Planning/plan_arc_results2_v_date.cfm?fromyear=1974&frommonth=01&fromday=01&to_year=2017&to_month=06&to_day=26&StartRow=" + (total_planning_applications - i*10)
window.onload = loop

//primary loop handler triggered by the window.onload event. See: https://stackoverflow.com/questions/588040/window-onload-vs-document-onload for more details.
function loop(){
    concatTables(superArray,document.getElementsByTagName("tbody")[0],function(){
        i++
        if(min_value < (total_planning_applications - i*10)){
            window.location.href = "http://www2.ashfield.gov.uk/cfusion/Planning/plan_arc_results2_v_date.cfm?fromyear=1974&frommonth=01&fromday=01&to_year=2017&to_month=06&to_day=26&StartRow=" + (total_planning_applications - i*10)
            window.onload = loop            
        }
    })
}

//merges a table from the Ashfield council's website with the mainArray (excluding headers)
function concatTables(mainArray,table,callback){
    if(mainArray=[]){
        mainArray.push(["RefNum","RefLink","Application","Location","Proposal","ADCDecision","ValidDate","Map","MapLink"])
    }
    arr = getArray(table)
    arr.shift()
    mainArray.push(arr)
}


//retrieves an array from the table on the Ashfield council's website
function getArray(table){
    var ret = []
    for(var i=0;i<table.children.length;i++){
        var row = table.children[i]
        var aRow = []
        var bSkip = false
        for(var j=0;j<row.children.length;j++){
            if (row.children.length==1){
                bSkip = true
                break;
            }
            aRow.push(row.children[j].innerText.trim().replace(/\r|\n/g," "))
            if(row.children[j].getElementsByTagName("a")[0]!=undefined){
                aRow.push(row.children[j].getElementsByTagName("a")[0].href)
            }
        }
        if(!bSkip){
            ret.push(aRow)
        } else {
            bSkip = false
        }
    }
    return ret
}

However, upon trying to execute the javascript code via the console, it halts after the initial loop. This interruption is due to security measures implemented by browsers to prevent cross-website scripting.

In this scenario, the objective isn't to navigate to another site but rather to a particular query string. Is there a method to achieve this without disrupting the javascript runtime?

If not, are there alternative solutions aside from utilizing something like Electron?

Answer №1

My innovative solution involves utilizing HTTP Requests instead of navigating to a website directly.

Rethinking the Approach

By leveraging HTTP Requests, we can streamline the process and minimize user disruption:

var total_planning_applications = 39437
var min_value = 30000
var base_ref = "http://www2.ashfield.gov.uk/cfusion/Planning/plan_arc_results2_v_date.cfm?fromyear=1974&frommonth=01&fromday=01&to_year=2017&to_month=06&to_day=26&StartRow="
window.mainArray = []
var i = 1

// Asynchronously make HTTP requests and handle them in a loop
httpGetAsync(base_ref + (total_planning_applications - i*10),loop)

function loop(docx){
    concatTables(window,docx.getElementsByTagName("tbody")[0],function(){
        i++
        console.log(`Processing...(${i})`)
        if(min_value < (total_planning_applications - i*10)){
            httpGetAsync(base_ref + (total_planning_applications - i*10),loop)      
        } else {
            console.log("All done!")
            console.log(JSON.stringify(window.mainArray))
        }
    })
}

// Merge table data from Ashfield council's website with mainArray
function concatTables(window,table,callback){
    if(window.mainArray.length==0){
        window.mainArray.push(["RefNum","RefLink","Application","Location","Proposal","ADCDecision","ValidDate","Map","MapLink"])
    }
    arr = getArray(table)
    arr.shift()
    window.mainArray = window.mainArray.concat(arr)
    callback()
}

// Extract array data from Ashfield council's table
function getArray(table){
    var ret = []
    for(var i=0;i<table.children.length;i++){
        var row = table.children[i]
        var aRow = []
        var bSkip = false
        for(var j=0;j<row.children.length;j++){
            if (row.children.length==1){
                bSkip = true
                break;
            }
            aRow.push(row.children[j].innerText.trim().replace(/\r|\n/g," "))
            if(row.children[j].getElementsByTagName("a")[0]!=undefined){
                aRow.push(row.children[j].getElementsByTagName("a")[0].href)
            }
        }
        if(!bSkip){
            ret.push(aRow)
        } else {
            bSkip = false
        }
    }
    return ret
}

// Async HTTP GET request function
function httpGetAsync(theUrl, callback){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
            parser = new DOMParser();
            xmlDoc = parser.parseFromString(this.responseText,"text/html")
            callback(xmlDoc);
        }
    }
    xmlHttp.open("GET", theUrl, true); // asynchronous 
    xmlHttp.send(); //null
}

My approach focuses on processing the XML document returned by httpGetAsync(), allowing for efficient data retrieval without impacting the user experience. By making recursive calls to the function, I was able to manage traffic effectively. Additionally, this technique could support simultaneous asynchronous calls if needed.

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

Suggestions for retaining dynamically modified HTML content post-response

My registration form includes input fields for username, email, and more. I have implemented a script that validates the form upon clicking the submit button, turning labels red when fields are empty. However, the submit button is also configured to send a ...

Storing LocalStorage configuration objects within an array in an Ionic list

I am currently experimenting with LocalStorage in order to store an array containing objects. The issue I'm facing is that the code snippet below is displaying an object in the console instead of returning an array. Due to this, my ion-list is unable ...

Vue - Child component not refreshing its data and triggering a re-render

In this scenario, I have the ability to upload a single LiteratureReview which can contain multiple Quote components. Essentially, I am dealing with parent-child relationships between LiteratureReview and Quote. Data retrieval and submission are done using ...

What is the best way to deactivate the first two columns of the header in Vue?

I am attempting to deactivate the draggable function for the first 2 columns. I have tried using options in the draggable plugin. :options="{disabled : 'Subject'}" However, this disables the draggable functionality for all headers. < ...

Is it necessary to encode special characters in a JSON object?

I am currently working on a code where I am taking a class and converting it to JSON format. Throughout my testing, all the content is surrounded by double quotes, for example: { "a" : "hello world ! '' this is john's desk" } I am wonderi ...

Vue Js and form-data Event: A deeper look into handling form

Hey there #Vue.js2 I'm facing an issue while trying to create a function that is called within a form submit event. This particular function needs both the EVENT and ID as parameters. The problem arises when I call this function, as I am unable to spe ...

How can I modify the value of a CSS animation rule in AngularJS?

I am looking to dynamically change the value assigned to stroke-dashoffset based on a custom input. @-webkit-keyframes donut-chart-1 { to { stroke-dashoffset: 100; } } @keyframes donut-chart-1 { to { stroke-d ...

Steps to create a clickable image input

How can I make an image clickable in an input with type=file? <label for="formFileSm" class="label_display form-label">avatar</label> <input class="width_input mx-auto form-control form-control-sm" id="fo ...

Having trouble with document.getElementById.innerHTML not displaying the correct content?

document.getElementById works in getting the element, but for some reason, the content disappears as soon as it is written in it. There are no errors on the console to indicate what's causing this behavior. I have been unable to identify the reason b ...

Does the delegated 'on' handler make any mention of the chosen element?

Is there a way to retrieve the selected element when using jQuery's on method within the handler, instead of the event target? In this context, none of the following code refers to the body element: $('body').on('click', 'h1& ...

Configuring Monaco Editor in React to be in readonly mode

Here is a code snippet to consider: import React from "react"; import Editor from "@monaco-editor/react"; function App() { return ( <Editor height="90vh" defaultLanguage="javascript" defa ...

Avoid wrapping elements

Is there a foolproof method or best practice to prevent an HTMLElement from wrapping? Specifically, I'm referring to elements with relative positioning. One possible solution could be using absolute elements and adjusting their left position based on ...

Incorporating groovy script into HTML: Is it possible, akin to embedding JavaScript

Can groovy script be embedded in HTML similar to JavaScript? I am interested in creating an onclick button event that utilizes groovy script instead of JavaScript. Thank you. ...

What techniques can be used to optimize the SEO of HTML generated by JavaScript? How does React.js go about achieving this

Is my webpage optimized for SEO if it was created using appendChild and innerHTML with JavaScript? Can react.js improve the SEO of a webpage? ...

Processing incoming requests with a loading interface in CodeIgniter

Is there a way to notify the user who sent the request whether or not the requested user will approve it? Optional: If there is no notification sent to the user who made the request, the requested user will have to wait for verification. For Example: Ima ...

Start numerous nodejs servers with just a single command

I currently have multiple Nodejs servers, each stored in its own separate folder within a root directory. Whenever I need to run these servers, I find it cumbersome to navigate through each folder and manually type nodemon *name*. The number of servers i ...

Executing Basic Authentication in Javascript through window.open()

After a user logs into my app, they have the option to download a CSV file from the server by clicking on a button. The URL for the download is secured with basic authentication. When attempting to open the URL using the code below: window.open('http ...

What is the most efficient way to automatically start the Webpack-dev-server every time a file is

Is there a way to automatically run and refresh webpack-dev-server when I am using the Atom package called AutoSave OnChange while running my application? This is my configuration for webpack-dev-server: devServer: { contentBase: './src/inde ...

`Is there a way to transfer a GUID from a View to JavaScript?`

I need to pass a GUID as a parameter from a View to a JavaScript function. However, I encountered an error message in Firefox stating "identifier starts immediately after numeric literal." Below is the code snippet from the View: onchange="updateOrder(&l ...

Closing the nested accordion will collapse all sections within the accordion

I'm currently facing an issue with my nested accordions. I've been attempting to nest them in a way that doesn't require writing additional jQuery code for each new one added. As an example, I've created a jsfiddle... https://jsfiddle. ...