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

Turning a text into a JSON data structure

How can I make JavaScript recognize a string as JSON? I have a function that only works when passed a JSON object. If I pass a string with the same format as JSON, it doesn't work. I want to find a way for the function to treat the string as JSON, ev ...

Navigating a roster of users in JavaScript

I'm dealing with a collection of user data stored in an array accountsade: [ { id: 0.4387810413935975, name: "Adrian", password: "345", userName: "nathanael" }, { id: 0. ...

Deactivating choices in Autoselect from Material UI

I am attempting to implement a feature in the autocomplete of material ui where options are disabled based on a specific condition. Each table row contains an autocomplete field, and when an option is selected in one row, it should be disabled in the next ...

What separates $(document).ready() from embedding a script at the end of the body tag?

Can you explain the distinction between running a JavaScript function during jQuery's $(document).ready() and embedding it in the HTML within script tags at the bottom of the body? Appreciate your insights, DLiKS ...

Reducing div size when clicked - Using JQuery version 1.9

I am looking to make a specific div shrink in size, while keeping all the data visible, each time a user clicks on a certain icon with the class legend-icon. For example, I want the div with the ID #Chart to shrink when clicked. This is the HTML code: &l ...

The useEffect hook is triggering multiple unnecessary calls

Imagine a tree-like structure that needs to be expanded to display all checked children. Check out this piece of code below: const { data } = useGetData(); // a custom react-query hook fetching data from an endpoint Now, there's a function that fin ...

Passing asynchronous data from method1 to method2 without impacting the functionality of the script responsible for fetching the asynchronous data in method1

When working with TypeScript, I encountered an issue while trying to invoke an external script called SPCalendarPro within a private method that asynchronously fetches data. The script is invoked in the following manner: private _getSPCalendarPro() { con ...

Utilize Angular 5 to implement URL routing by clicking a button, while also preserving the querystring parameters within the URL

I have a link that looks like this http://localhost:4200/cr/hearings?UserID=61644&AppID=15&AppGroupID=118&SelectedCaseID=13585783&SelectedRoleID=0 The router module is set up to display content based on the above URL structure { path: & ...

Is it possible to customize the CSS styles of a jQuery UI modal dialog box?

Having trouble with my CSS styles not applying to a dialog modal added to my website using jQuery UI, even when using '!important'. I suspect that the predefined jQuery or UI CSS styles from a CDN link are preventing me from overriding them. The ...

Understanding the scope within a .when .done function in jQuery

I'm currently grappling with accessing a variable from within a .when.done function. Take a look at this illustrative example: var colviews = { 1: true, 2: true, 3: false } $.when( $.getScript( "/mckinney_images/jquery.tablesorter. ...

The div layer is positioned above the flash object

I have successfully implemented a method where I position a div over a webpage containing a flash object. This absolutely positioned div has a high z-index and captures click events. The main goal is to trigger the click event on the div when the flash obj ...

Adjust the size of an iFrame's content according to the dimensions of the iFrame

I am looking to use an iFrame for embedding a map, and my goal is to resize the map according to the values in the iFrame tag. Most tutorials I have found focus on auto-sizing the iFrame based on content, which is not what I need. Just to make it clear, I ...

Angular 6 - The state of the expression was altered after it was verified, different types of constructions

During the build process in debug mode with ng build, I am encountering errors in some components. However, when I switch to production mode using ng build --prod, these errors disappear. I am curious as to why this discrepancy is occurring. Error: Expre ...

While attempting to import modules in Visual Studio Code, an error message appears stating "Unexpected token {"

Greetings! I am currently using Visual Code to run my project and would like to share my code with you. In the file external.js: export let keyValue=1000; In the file script.js: import {keyValue} from './external.js'; console.log(keyValue); ...

Changing Highcharts Donut Chart Title Text via Legend Item Click in React

Utilizing React. In my Highcharts donut chart, there are 5 legend items of type 'number' and a 'title text' (also type: number) displayed at the center. The title text represents the sum of all the legend items. However, when I click o ...

What are some ways I can effectively implement Tanstack Query's useMutation function?

I am trying to implement useMutation similar to useQuery in my code. However, I encountered an issue where the data is returning as undefined and isError is false. Can anyone help me understand why this is happening and how I can resolve it? `import { us ...

Generating a multidimensional associative array based on user inputs from a form

What is the best way to transform form input data into a multidimensional associative array? This is how the form appears: <div id="items"> <h4>Engraving Text</h4> <div class="item" data-position="1"> <h4 id="en ...

Tips for triggering functions when a user closes the browser or tab in Angular 9

I've exhausted all my research efforts in trying to find a solution that actually works. The problem I am facing is getting two methods from two different services to run when the browser or tab is closed. I attempted using the fetch API, which worke ...

What steps should be taken to create a two-column table from a given list of items?

I am trying to display a list of words in two columns, one word after another from left to right. Here is the desired table structure: <table id="wordTable"> <tr> <td>ac </td> <td>bd </td> </tr> ...

Error encountered: Multer does not recognize the field when attempting to upload multiple files in a node.js environment

I would like to upload two files in one request using Node.js and I am utilizing multer for this task. Here is my request in Postman: Additionally, I am using multer in routing: router.post( "/Create", UploadProfileHandler.single("sign ...