Simple Javascript extension to change playback speed not working

853 views Asked by At

I have a simple playback speed setter for any HTML tagged videos (YouTube).

When I click the 2.25 button that's supposed to change the speed to 2.25, nothing happens. I don't get an error message.

But when I open the browser console and type "document.querySelector('video').playbackRate = 2.25", the video changes its speed fine.

What is wrong?

playspeed.js

browser.tabs.executeScript(
{ code: `document.getElementById('speed225').onclick = function () { document.querySelector('video').playbackRate = 2.25; 
}` })

speed-buttons.html

<!DOCTYPE html>

<html>

<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css" />
</head>

<body>
    <div id="popup-content">
        <div class="button" id="speed225">2.25</div>
    </div>
    <script src='playspeed.js'></script>
</body>

</html>

style.css

html, body {
    width: 100px;
}

.button {
    margin: 3% auto;
    padding: 4px;
    text-align: center;
    font-size: 1em;
    cursor: pointer;
    background-color: lightgray;
}

.button:hover {
    background-color: rgb(196, 230, 196);
}

manifest.json

{
    "manifest_version": 2,
    "name": "Video Playback Speed Controller (Menu Bar)",
    "version": "1.0",
    "description": "Adds buttons in the menu bar to change playback speed for HTML video tagged videos.",
    "icons": {
        "48": "icons/playback-icon-48.png"
    },
    "permissions": [
        "activeTab"
    ],
    "browser_action": {
        "default_icon": "icons/playback-icon-32.png",
        "default_title": "Change Video Speed",
        "default_popup": "speed-buttons.html"
    }
}
1

There are 1 answers

0
wOxxOm On

The speed225 button is inside the popup so its listener cannot be inside executeScript, which injects the code inside the web page as a content script.

Use this:

document.getElementById('speed225').onclick = function () {
  browser.tabs.executeScript({
    code: "document.querySelector('video').playbackRate = 2.25;"
  });
};

See also How to open the correct devtools console to see output from an extension script?