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

此生再无相见时 提交于 2019-12-10 15:23:21

问题


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.

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.

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

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

I will appreciate any help.


回答1:


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.

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.

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.

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>');
}



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



来源:https://stackoverflow.com/questions/21869204/userscript-is-there-a-way-to-inject-jquery-code-into-angularjs-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!