Search code examples
javascriptgreasemonkeyuserscriptstampermonkeygreasemonkey-4

Using the same userscript to run different code at different URL's


I know it is possible to run a script on different URL's by adding @include statements, but it is possible to run different sets of code based on the URL?

My script currently works properly but I had to break it into 5 separate userscripts and it feels kind of sloppy.


Solution

  • To switch what code runs, per URL, use if() or switch() statements against parts of the location objectDoc.

    To avoid false positives and side effects, it is best to just test that property that is most discriminating (usually hostname and/or pathname).

    For example, for a script running on different sites:

    if (/alice\.com/.test (location.hostname) ) {
        // Run code for alice.com
    }
    else if (/bob\.com/.test (location.hostname) ) {
        // Run code for bob.com
    }
    else {
        // Run fall-back code, if any
    }
    
    // Run code for all sites here.
    


    Or, for same-site, different pages:

    if (/\/comment\/edit/.test (location.pathname) ) {
        // Run code for edit pages
    }
    else if (/\/comment\/delete/.test (location.pathname) ) {
        // Run code for delete pages
    }
    else {
        // Run fall-back code, if any
    }
    
    // Run code for all pages here.
    


    Note the use of escape \.
    .test() is used for the awesome power of regex. For example,
    /(alice|bob)\.com/.test (location.hostname).