Search code examples
youtubegreasemonkeyuserscripts

Greasemonkey script testfor url & add parameter


I want to check for site youtube.com and if it is a video site (includes watch?v=) then add &rel=0 to the url. Pseudocode:

if url = youtube.com/watch?v=* |then newurl = url + &rel=0

More examples:

  • youtube.com -> youtube.com
  • youtube.com/feed/subscriptions -> youtube.com/feed/subscriptions
  • youtube.com/watch?v=ikIXmUUumjg -> youtube.com/watch?v=ikIXmUUumjg&rel=0
  • youtube.com/watch?v=ikIXmUUumjg&t=0 -> youtube.com/watch?v=ikIXmUUumjg&t=0s&rel=0

Solution

  • The trick is to use modern javascript to replace URL without redirecting. Second trick is to know that window.location contains parsed URL divided in sections (hostname, path, query arguments...).

    // ==UserScript==
    // @name        window rel youtube
    // @namespace   util
    // @match       *://www.youtube.com/*
    // @version     1
    // @grant       none
    // ==/UserScript==
    const watchRegex = /watch\?v=/i
    if(window.location.href.indexOf("watch?v=")!=-1 && window.location.search.indexOf("rel=0")==-1) {
        console.log("changing url");
        var baseURL = window.location.origin + window.location.pathname+window.location.search+"&rel=0"+window.location.hash;
        window.history.pushState({"pageTitle":document.title},"", baseURL);
    }
    else {
        console.log("No change in url");
    }