用户脚本 - 有没有办法将jquery代码注入angularjs dom? [英] Userscript - Is there a way to inject jquery code into angularjs dom?

查看:94
本文介绍了用户脚本 - 有没有办法将jquery代码注入angularjs dom?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试为一个网站创建用户脚本。我无法更改网站的任何源代码,因为它不是我的。
网站到处都在使用AngularJS控制器。
我正在研究如何做到这一点,但没有成功。

So I'm trying to create userscript for one website. I cannot change any source code of website as it is not mine. Website is using AngularJS controllers everywhere. I'm researching for couple of days how to do this, but not successful.

所以我试图注入代码 $(。nav)。after(< div> test< / div>); 当我通过Firefox开发者控制台执行此操作时,它正在工作,但为什么它不起作用时我试图通过Userscript来做。

So I'm trying to inject code $(".nav").after("<div>test</div>"); it is working when I do it via Firefox Developers Console, but why it doesn't work when I'm trying to do it via Userscript.

我确实添加了 $(function(){...}); thingy to code所以它在DOM准备好之后触发句柄,但它仍然不起作用。

I did add $(function () { ... }); thingy to code so it fires handle after DOM is ready, but it still doesn't work.

有没有办法做到这一点?
我非常想了解AngularJS的工作原理......

Is there a way to do it? I'm desperate of understanding how AngularJS works...

我将不胜感激任何帮助。

I will appreciate any help.

推荐答案

Angular在加载页面后很好地修改了DOM,所以你需要一些方法来等待你关心的事件或节点。

Angular modifies the DOM well after the page is loaded, so you need some way to wait for the events or nodes you care about.

此外,您必须保持代码(尤其是jQuery)不会干扰页面的代码。这意味着你应该努力保持沙盒开启。

Also, you must keep your code (especially jQuery) from interfering with the page's code. This means you should endeavor to keep the sandbox switched on.

对于Firefox + Greasemonkey或Chrome + Tampermonkey(或大多数支持的引擎@require 指令),您可以使用 waitForKeyElements()实用程序 @grant 指令来实现这些目标。

For Firefox+Greasemonkey or Chrome+Tampermonkey (or most engines that support the @require directive), you can use the waitForKeyElements() utility and the @grant directive to accomplish these goals.

这个完整的示例脚本适用于FF + GM和Chrome + TM:

This complete, sample script will work on both FF+GM and Chrome+TM:

// ==UserScript==
// @name     _Add a div after .nav elements
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @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 (".nav", addTestDiv);

function addTestDiv (jNode) {
    jNode.after ('<div>test</div>');
}


如果您使用的引擎不支持 @require 指令(如直接的Chrome用户脚本),请切换! Tampermonkey值得转换。

If you are using an engine that doesn't support the @require directive (like a straight Chrome userscript), switch! Tampermonkey is worth switching to.

这篇关于用户脚本 - 有没有办法将jquery代码注入angularjs dom?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆