Ways to update all URLs on a page with ajax functionality

My userscript is designed to modify the href of specific links on an IP-direct Google search page:

// ==UserScript==
// @name     _Modify select Google search links
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @include  http://62.0.54.118/*
// ==/UserScript==

var qLinks  = document.querySelectorAll ("a[href*='?q=']");

for (var J = qLinks.length - 1;  J >= 0;  --J) {
    var oldHref = qLinks[J].getAttribute ('href');
    var newHref = oldHref.replace (/\?q=/, "?&q=");

    //console.log (oldHref + "\n" + newHref);
    qLinks[J].setAttribute ('href', newHref);
}


Although it functions properly on the initial page, when navigating through pagination links, the script ceases to work due to AJAX loading subsequent pages.

@Brock Adams suggested using waitForKeyElements(), but I struggled to implement it.

I have come across discussions like stackoverflow.com/questions/10888326/executing-javascript-script-after-ajax-loaded-a-page-doesnt-work, but integrating them has been challenging.

Is there a way to adapt this script to modify links on an AJAX page such as:

http://62.0.54.118/search?&q=42&oq=42&sourceid=chrome&ie=UTF-8&filter=0#filter=0&q=42&start=10

Answer №1

To convert static-page code to utilize waitForKeyElements(), you need to complete 3 or 4 simple tasks:

  1. Include jQuery and waitForKeyElements in the script's metadata section.
  2. Select the appropriate jQuery selector for waitForKeyElements, usually the same as what is used for querySelectorAll().
  3. Adjust any loop-driven code for a single node, making use of jQuery where necessary.
  4. In this scenario, Google updates links on pagination without using AJAX. Therefore, ensure the callback function returns true.

When combining all these steps, the entire script based on the initial code provided would look like this:

// ==UserScript==
// @name     _Modify select Google search links
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @include  http://62.0.54.118/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0. It restores the sandbox.
*/
waitForKeyElements("a[href*='?q=']", changeLinkQuery);

function changeLinkQuery(jNode) {
    var oldHref = jNode.attr('href');
    var newHref = oldHref.replace(/\?q=/, "?&q=");

    jNode.attr('href', newHref);

    return true;
}

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

Guide on sending an ajax request following a successful submission of a form using Contact Form 7, all while incorporating multiple tabs within Bootstrap 5

I have a scenario where I am utilizing multiple Contact Form 7 Forms within Bootstrap 5 tab panels. My goal is to trigger an Ajax request to send data after each successful form submission. To achieve this, I implemented the use of wpcf7mailsent event list ...

JSONP error: "Syntax error - token not expected"

While attempting to perform a JSONP AJAX request, an error was thrown: Uncaught SyntaxError: Unexpected token I'm puzzled about what is wrong in my code. Can someone assist? $.ajax({ url: 'http://api.server32.trustklik.com/apiv1/website/ ...

Linking asynchronous functions does not function properly

I've been attempting to link two asynchronous functions together, but it appears that the second function is running before the first one. Below is the code snippet: function performAction(e) { const ZIP = document.getElementById('zip').valu ...

Discover the position of a dynamically added element

Is there a way to identify the specific dynamically added checkbox that was clicked, whether by index or name? I came across a similar question with a solution in this JSFiddle: JSFiddle Instead of just displaying "clicked", I would like it to show someth ...

what sets apart parseint from minus

Typically, my approach for parsing numbers in JavaScript involves the following code snippet: var x = "99" var xNumber = x - 0 as opposed to using: var xNumber = parseInt(x) I am curious to know if there are any potential issues with this method in ter ...

Utilizing the static folder feature in Express on a shared hosting platform

Struggling with implementing a static folder in my Node.js+Express application, I keep encountering a frustrating 404 error. After setting up the basic structure using express project_name, here is the simplified folder layout: app.js /views \-- la ...

JavaScript Empty Input Field when Duplicating Node

I am seeking advice on how to clear the textboxes when an HTML form is cleared. The following JS code runs onclick: var counter = 0; function moreField() { counter++; var newFields = document.getElementById('readroot').cloneN ...

Here is an example of how to transfer a value from PHP to a jQuery function in the code snippet provided

This is an example of my code. It is functioning properly even without passing a value. function displayMessage(text) { alert(text); } <button type="button" id="button" class="btn btn-success" onclick="displayMessage("Hello");"> Click Me </ ...

JavaScript is failing to match the float and string values

Trying out this code snippet: if(total === balance) { alert("test passed"); } else { alert("test failed"); } In this scenario, total = 10; and balance = 10.00;, yet the output is "test failed". ...

Should we be validating passwords through mongoose middlewares - is this the right approach?

I am currently using the validator package for email validation in my project. const validator = require('validator'); email: { type: String, required: [true, 'User must have a email'], unique: true, lowercase: true, / ...

Transferring JSON encoded information from a controller to a view via ajax within the CodeIgniter framework

After selecting data from the controller, I want to display it on the view using a Bootstrap template. To achieve this, I need to place the following code in my controller: $data['sidebar']='member/dokter/sidebar_psn'; $data['cont ...

Conceal the Ajax Div and display the Loader Div while waiting for the data to be

Trying to show a loader div until the Ajax-populated div is returned. Want to hide "responseDiv" until it's filled with Ajax data and display a loading div in the meantime. #loading { background: url('images/loading.gif') no-repeat cent ...

Invoke function within bxslider callback

I am attempting to utilize a custom function within a bxslider callback, but unfortunately, the function is not being recognized (specifically: Uncaught Reference Error: nextSlideCustom() is not a function) The current code snippet I have is as follows: ...

Tips for storing the state using Localstorage?

Greetings to the person reading this message! I am relatively new to programming and I have a query... I created a Navigation bar: body > div > nav > div > ul > li*10 I have implemented the styling in CSS. //Navigation Bar const list = ...

Is there an equivalent of the quit method in Selenium & Chromedriver for PHP webdrivers, or do they only have the close() method? I'm curious about the wire protocol commands used in

If I were to mimic the functionality of Selenium's Java Webdriver's quit() method using a PHP Webdriver or any other programming language, how would I go about it? Is it a JSON wire protocol command or something different? Despite my efforts, I ...

The input type "number" does not seem to be compatible with the currency pipe feature

The currency pipe seems to not be working when using the input type number. The web page is not displaying any value. I have searched various blogs and it appears that the currency pipe only works with input type text, but my requirement necessitates the ...

Using Jquery to retrieve servlet session data

Having trouble displaying a div using servlet session attributes & JQuery. Explanation might be tricky without context. On the "result.jsp" page, there's a "Generate URL" link, an empty input text field, and an "addThis" div. When clicking on the lin ...

What is the best way to utilize Link navigation in order to navigate away from a blocked route in the latest version of Next.js,

DISCLAIMER: I raised this issue on the Next.js GitHub repository, but it was closed without recognition. The solution provided did not resolve my problem, leading me to seek help here. The Issue at Hand I have created a demo app (accessible here) on Code ...

Getting the output from AJAX when the onreadystatechange event occurs

Struggling with retrieving a value from a function and storing it in a variable? Getting an "undefined" result due to JavaScript's asynchronous nature? Unsure how to fix this using "callbacks" or "promises"? Check out the code snippet below. The goal ...

How to add a new row to a Kendo grid with a unique custom styling

I am looking for a way to insert new data into a Kendo grid, but I want the added row to have a custom class so that I can style it with a different background color. How can I achieve this? I have searched through all the documentation but couldn't f ...