简体   繁体   English

用户脚本-有没有办法将jQuery代码注入angularjs dom?

[英]Userscript - Is there a way to inject jquery code into angularjs dom?

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. 网站到处都在使用AngularJS控制器。 I'm researching for couple of days how to do this, but not successful. 我正在研究几天如何做到这一点,但没有成功。

So I'm trying to inject code $(".nav").after("<div>test</div>"); 所以我想注入代码$(".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. 当我通过Firefox开发人员控制台进行操作时,它可以工作,但是当我尝试通过用户脚本进行操作时,为什么它不起作用。

I did add $(function () { ... }); 我确实添加了$(function () { ... }); thingy to code so it fires handle after DOM is ready, but it still doesn't work. 编写代码很麻烦,因此在DOM准备就绪后会触发处理,但是仍然无法正常工作。

Is there a way to do it? 有办法吗? I'm desperate of understanding how AngularJS works... 我很想了解AngularJS的工作原理...

I will appreciate any help. 我将不胜感激。

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. 页面加载后,Angular会很好地修改DOM,因此您需要某种方式来等待您关心的事件或节点。

Also, you must keep your code (especially jQuery) from interfering with the page's code. 另外,您还必须防止您的代码(尤其是jQuery)干扰页面的代码。 This means you should endeavor to keep the sandbox switched on. 这意味着您应该努力保持沙箱处于打开状态。

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. 对于Firefox + Greasemonkey或Chrome + Tampermonkey(或大多数支持@require指令的引擎),可以使用waitForKeyElements()实用程序@grant指令来实现这些目标。

This complete, sample script will work on both FF+GM and Chrome+TM: 此完整的示例脚本可在FF + GM和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>');
}



If you are using an engine that doesn't support the @require directive (like a straight Chrome userscript), switch! 如果您使用的引擎不支持@require指令(例如直接的Chrome用户脚本),请切换! Tampermonkey is worth switching to. Tampermonkey值得切换。

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

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