开发者

Use a userscript as a regular javascript?

开发者 https://www.devze.com 2023-03-22 06:16 出处:网络
If I have a userscript that I\'ve found online, and I\'d like to incorporate it into a website as a normal javascript (i.e. not userscript), how can I do that?

If I have a userscript that I've found online, and I'd like to incorporate it into a website as a normal javascript (i.e. not userscript), how can I do that?

This seems like it would be something pretty simple but I am new to javascript and userscript, hopefully somebody can help me out.

For example, I found this userscript: "Convert UPS and FedEx Tracking Numbers to Links"...

Which will parse a page for regular expressions matching any UPS/FEDEX/USPS tracking number, and convert them to links to the respective carriers' tracking website to track that number.

This works great as a userscript, but I would like it t开发者_如何学运维o be automatic on the site I am working on (not require visitors to download/install a userscript).

How can I use this userscript as a regular javascript?


UserScripts are usually executed after the page DOM is loaded, to make sure that the page contents can be completely accessed. So, you need some kind of mechanism to achieve that. But this is a bit tricky since older versions of IE need special treatment.

Doing it manually would require about 30 lines of code. Libraries like jQuery offer a ready() method like so:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function () {

    // put userScript here

});
</script>


It should just be a matter of linking it like any other Javascript file:

Save it as foo.js, then in your html,

<body>
<!-- body code here -->
<script src="foo.js"></script>
</body>


You can just put it in a JS file and include the file in your page.

UserScripts contain normal Javascript code, but are executed by a plugin rather than being on the page.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号