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.

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top