1

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

kuro
  • 57
  • 5
  • 1
    See [How to detect page navigation on YouTube and modify its appearance seamlessly?](https://stackoverflow.com/a/34100952). – wOxxOm Sep 05 '22 at 06:05
  • Thanks alot, will look into this. Knew simple navgation isnt gonna work that easily – kuro Sep 05 '22 at 06:27

1 Answers1

0

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
);
Dhan
  • 501
  • 1
  • 8
  • 21
  • Yeah sadly this didnt work, the setTimeout method just make the browser keep on reloading the youtube site every 2sec indefinitely – kuro Sep 05 '22 at 04:53
  • You have to write it inside a function and then call the function. if the timeout code is out open in the code it will continuously reload page every 2 seconds. – Dhan Sep 05 '22 at 04:55
  • Well i did try calling the function in the switch case but sadly it still wont force reload on autoplay or selecting the video – kuro Sep 05 '22 at 05:04