简体   繁体   English

如何让用户脚本处理尚不存在的功能和元素?

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

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. 在为各种网站编写用户脚本时,我经常遇到处理在执行时尚不存在的元素或JS函数的问题。 I'd like to know how to get to those functions or elements. 我想知道如何使用这些功能或元素。
An obvious solution is a setTimeout , but that's very inelegant. 一个明显的解决方案是setTimeout ,但这非常不雅致。 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. 我还尝试了各种事件,例如DOMContentLoadedwindow.onload ,但我经常发现这些事件还为时过早,因为事后会动态生成/加载内容和代码。

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. 如果要加载脚本文件,则可以加入onload事件。 If you do an AJAX call you can hook into the onreadystatechange event. 如果您进行AJAX调用,则可以加入onreadystatechange事件。

These are some useful native events. 这些是一些有用的本地事件。

You can also make more custom events by using Promises. 您还可以使用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. requirejs可能值得一看,只是看看它们是如何工作的。

As for promises, this is a good read: What's so great about JavaScript Promises? 至于Promise,这是一本好书: JavaScript Promises有什么优点

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. 同样,请记住,例如,Chrome中的用户脚本已被沙箱化,您将需要跳过一两个循环才能访问目标页面上的代码。 For small scripts, I suggest the "Location Hack". 对于小型脚本,我建议使用“位置破解”。 https://stackoverflow.com/a/5006952/125938 https://stackoverflow.com/a/5006952/125938

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM