Search code examples
javascriptjqueryuserscripts

jQuery.noConflict(); for userscript


Hello I'm trying to add jQuery to my Userscript that I'm creating.

I've tried:

$ = jQuery = window.jQuery;

Doesn't work $ is undefined. My other choice is:

$ = unsafeWindow.jQuery;

Which works and all, but I receive this error:

Unexpected token e

That's not even part of my code, it points to something on the website. However, I noticed that the website I'm creating a userscript for uses this:

jQuery.noConflict();

Is that the cause of this? And I can't import the jQuery library because I'm trying to make custom emotes for a shoutbox which uses XMLHttpRequests(AJAX) and it prevents the chat from working when I load an external library.

I've been trying to fix this for 6 hours and I'm getting nowhere. I'd probably turn to just using DOM if nothing works =/.

Thank you for all that helped and if you need any information from me I'll gladly share it.


Solution

  • I just looked at another userscript and this is the solution!

    (function wrapper(window, injectNeeded, undefined) {
    
    // Script injection if needed.
    if (injectNeeded) {
        var script = document.createElement('script');
        script.textContent = '(' + wrapper + ')(window, false)';
        document.body.appendChild(script);
        document.body.removeChild(script);
        return;
    }
    
    var $,
        jQuery;
    
    $ = jQuery = window.jQuery;
    
     console.log($('a').length + "links on this page.");
    })(this.unsafeWindow || window, window.chrome ? true : false);
    

    Source: https://raw.github.com/cletusc/Userscript--Twitch-Chat-Emotes/master/script.user.js#bypass=true