How to have your user script deal with functions and elements that don't exist yet?

StackOverflow https://stackoverflow.com/questions/20423760

  •  29-08-2022
  •  | 
  •  

Frage

When writing user scripts for various websites I often come across the problem of dealing with elements or JS functions that don't exist yet at the time of execution. I'd like to know how to get to those functions or elements.
An obvious solution is a setTimeout, but that's very inelegant. I've also experimented with the various events like DOMContentLoaded and window.onload, but I often find that these events are still too early, due to content and code being dynamically generated/loaded afterwards.

War es hilfreich?

Lösung

Make sure that whatever you're loading emits an event, that you can hook into.

If you're loading a script file you can hook into the onload event. If you do an AJAX call you can hook into the onreadystatechange event.

These are some useful native events.

You can also make more custom events by using Promises.

var modules = {/* */};
var foo = modules.load("foo"); // returns a promise
foo.done(function (foo_module) {
    // we now have the foo-module
});

requirejs might be worthwhile to look at, just to see how they do things.

As for promises, this is a good read: What’s so great about JavaScript Promises?

Andere Tipps

Make sure you're not doing something wrong before jumping to conclusions. Like, remember that user scripts in Chrome for example, are sandboxed, and you'll need to jump through a hoop or two to even access code on the target page. For small scripts, I suggest the "Location Hack". https://stackoverflow.com/a/5006952/125938

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top