Redirecting youtube videos when clicked or autoplay

Viewed 27

Was trying to make my first extension, I am having trouble redirecting specific youtube video after autoplay or when i clicked on it.

Redirection work when i went straight to the URL on the browser and when i reload but not after autoplay or selecting the video on the youtube site itself

Here's an example of my js code

//contentscript.js

const urlParams = new URLSearchParams(window.location.search) ;
switch (urlParams.get('v')) {
    case "abcxxx":     
    window.location.replace("https://www.youtube.com/watch?v=123xxx");
    break;
    case "defxxx":
    window.location.replace("https://www.youtube.com/watch?v=456xxx");
    break;
}

Here's my manifest file

{
    "name": "Test1st",
    "description": "Test",
    "content_scripts": [
        {
          "matches": [ "https://www.youtube.com/*"],
          "js": [ "contentscript.js"],
          "run_at": "document_start",
          "all_frames": true
        }
      ],
    "content_security_policy": "script-src 'self' https://ssl.google-analytics.com; object-src 'self'",
    "icons": {
        "128": "img/128.png",
        "16": "img/16.png",
        "48": "img/48.png"
    },
    "manifest_version": 2,
    "page_action": {
        "default_icon": {
            "128": "img/128.png",
            "16": "img/16.png",
            "48": "img/48.png"
        },
        "default_title": "xxxxxx"
    },
    "permissions": ["tabs", "cookies", "contextMenus", "http://*/*", "https://*/*", "webRequest", "webRequestBlocking", "webNavigation"],
    "version": "2015.21.9.1",
    "web_accessible_resources": [ "*" ]
}

Not quite sure if this can be done purely on js

1 Answers

Try it like this

const urlParams = new URLSearchParams(window.location.search) ;
var newUrl = "";
switch (urlParams.get('v')) {
    case "abcxxx":     
    newUrl = "https://www.youtube.com/watch?v=123xxx";
    break;
    case "defxxx":
    newUrl "https://www.youtube.com/watch?v=456xxx";
    break;
}

setTimeout(function(){ 
    window.location.replace(newUrl);
    2000
);
Related