Home > Web Front-end > JS Tutorial > How Can I Execute a Greasemonkey Script Multiple Times on the Same Page Without Refreshing?

How Can I Execute a Greasemonkey Script Multiple Times on the Same Page Without Refreshing?

Susan Sarandon
Release: 2024-11-16 11:12:02
Original
1043 people have browsed it

How Can I Execute a Greasemonkey Script Multiple Times on the Same Page Without Refreshing?

Executing Greasemonkey Scripts Multiple Times Per Page

As a new user to Greasemonkey and web development, you encounter a challenge: running a userscript multiple times on the same page without refreshing the page. This is necessary for scenarios like Ajax-driven Amazon searches, where you aim to insert a custom element into search results as they appear.

The effective solution recommended by experienced users is the waitForKeyElements() utility. It allows you to specify a target element on the page and register a callback function that will execute every time the target element is added or modified.

To demonstrate its usage, let's consider a modified script for altering Amazon search results:

// Greasemonkey script to alter Amazon search results
// ==UserScript==
// @name     _Amazon Search, alter results
// @include  http://www.amazon.com/s/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==

function addCustomSearchResult (jNode) {
    // Inject your custom element
    jNode.prepend (
        '<div>
Copy after login

Here's how it works:

  • The waitForKeyElements() function monitors the target element (#atfResults in this case) and calls the callback function (addCustomSearchResult) whenever the element is added or modified.
  • In the callback function, you can inject your custom content into the search results div.
  • Since this process occurs without page refreshes, your custom element will appear in the search results every time a new Ajax request is made.

The above is the detailed content of How Can I Execute a Greasemonkey Script Multiple Times on the Same Page Without Refreshing?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template