Compare commits

...

74 Commits

Author SHA1 Message Date
joshpatra 5c20d7ae0b v5.0.0-beta.1 2026-03-31 15:03:56 -04:00
joshpatra 068e65f62f chore: update manifest.json 2026-03-31 15:03:23 -04:00
joshpatra b0498cd1d7 Merge dev 2026-03-31 15:01:17 -04:00
joshpatra 52080a4185 Add .vscode to .gitignore 2026-03-31 15:01:16 -04:00
joshpatra 85215ae54b Merge main: update beta install instructions 2026-03-31 14:53:41 -04:00
joshpatra 9f8c235cea Merge dev: update beta install instructions 2026-03-31 14:53:41 -04:00
joshpatra 30c5a7dbe3 Update beta release install instructions for Firefox XPI auto-install 2026-03-31 14:53:30 -04:00
joshpatra 597c7a8af5 Merge main: fix beta signing via AMO unlisted 2026-03-31 14:48:47 -04:00
joshpatra d215ad4224 Merge dev: fix beta signing via AMO unlisted 2026-03-31 14:48:46 -04:00
joshpatra 705667b532 Fix beta signing: use AMO unlisted channel instead of unsigned build
Unsigned XPIs are blocked by Firefox. Beta releases must be signed via
AMO --channel unlisted to allow manual installation.
2026-03-31 14:48:37 -04:00
joshpatra df18e638c2 Merge main: fix XPI rename glob 2026-03-31 14:44:46 -04:00
joshpatra 9ff3ce4f74 Merge dev: fix XPI rename glob 2026-03-31 14:44:39 -04:00
joshpatra 11e3518902 Fix XPI rename: web-ext build outputs .zip not .xpi 2026-03-31 14:44:24 -04:00
joshpatra 91dc47f5a8 Merge main: restructure CI/CD workflow 2026-03-31 14:39:11 -04:00
joshpatra 36a60bbe34 Merge dev: restructure CI/CD workflow 2026-03-31 14:39:04 -04:00
joshpatra ea48170e11 Restructure CI/CD: tag-based releases, branch-based routing
- v* tags without -beta → sign & submit to AMO (listed/public)
- v*-beta tags → GitHub prerelease XPI for self-hosting
- dev branch pushes → lint-only CI, no release artifacts
2026-03-31 14:38:46 -04:00
joshpatra 3bcb36f6d0 Merge branch 'dev' into beta 2026-03-31 14:22:24 -04:00
joshpatra f2cf8b6205 Fix workflow: use system jq, tag-based builds 2026-03-31 14:22:14 -04:00
joshpatra 2747c15924 Test beta prerelease 2026-03-31 14:18:49 -04:00
joshpatra 5e7d5d6d21 Merge branch 'dev' into beta 2026-03-31 14:18:32 -04:00
joshpatra 6045ac5688 Fix GitHub Actions jq error 2026-03-31 14:18:30 -04:00
joshpatra 38174a2a76 Test beta prerelease 2026-03-31 14:15:17 -04:00
joshpatra 8569fa6e33 ci: add Firefox AMO + GitHub release workflow 2026-03-31 14:11:05 -04:00
joshpatra 30ba6585b0 fix: import/export 2026-03-31 14:06:17 -04:00
joshpatra 8d48dcccca fix: dragging from middle positions 2026-03-31 01:08:57 -04:00
joshpatra 75acaada8d feat: uniform spacing between controls 2026-03-31 01:02:43 -04:00
joshpatra 6d993edf50 feat(ui): configurable control bar, popup controls, and settings overhaul 2026-03-31 00:48:47 -04:00
joshpatra b4030f91dd feat: settings update 2026-03-30 16:25:03 -04:00
joshpatra 44c9c576ed Add donation footer to options page 2026-03-30 15:46:54 -04:00
joshpatra 72f590cd02 fix: mouseover behavior 2026-03-29 18:18:02 -04:00
joshpatra caf75b3e54 fix: closes #17 for real this time 2026-03-29 16:22:43 -04:00
joshpatra 37d1831b8b feat: a minimal fix to try and close #17 2026-03-29 15:28:10 -04:00
joshpatra 14e37c62d5 feat: hide with controls timer for non-youtube websites, site-specific rules for it too 2026-03-29 15:13:59 -04:00
joshpatra 03f5dbaa96 fix: import/export, and saving settings fixed 2026-03-29 14:43:25 -04:00
joshpatra 8b30005fb2 chore: swap versioning for Github and Firefox 2026-03-29 12:03:01 -04:00
joshpatra f385074905 chore: replace the default disabled websites with example domains 2026-03-28 19:15:37 -04:00
joshpatra a51801e7c3 fix: made hide with controls site-specific accidentally 2026-03-28 19:08:14 -04:00
joshpatra cd5e4bee9f feat: add setting to hide controller with YouTube controls, restoring a bug from before lol 2026-03-28 18:57:48 -04:00
joshpatra 4d34c8754d fix: expand from right for middle positions 2026-03-28 17:31:18 -04:00
joshpatra 194acacab4 fix: z-index regression, fullscreen top padding 2026-03-28 17:25:34 -04:00
joshpatra 6cf4ef3f93 feat: add import/export settings with modular architecture 2026-03-28 16:30:37 -04:00
joshpatra 104b828d47 feat: improve removal button visibility and standardize site rules 2026-03-28 16:03:06 -04:00
joshpatra 318598b8cf fix: restore default keybinding population in options 2026-03-28 16:02:50 -04:00
joshpatra 5616778421 feat: Site-Specific Rules stash pop, cleaned up some settings 2026-03-28 11:38:13 -04:00
joshpatra bec32b4c0e Video controller: adjust bottom padding for controller locations 2026-03-28 11:31:06 -04:00
joshpatra 2832598881 feat: add the 'Preferences' pane to the Addon Menu 2026-03-28 10:00:53 -04:00
joshpatra 079834ca72 fix: bring back blocklisted websites, must've accidentally removed them 2026-03-28 03:31:48 -04:00
joshpatra d44010f7a3 feat: Default controller location, easy moving of Controller with new shortcut 2026-03-28 03:21:50 -04:00
joshpatra b02cdb14b3 feat: Hijack Youtube's native playback speed controller for some performance gain, at least up to 2.0, and afterwards, use the nudging mechanism 2026-03-28 02:54:33 -04:00
joshpatra be8342fa18 fix: nudge now works on YouTube embeds on sites like KhanAcademy, refactor: use querySelectorAll instead of recursively calling scanNodeForMedia on every element in the DOM 2026-03-28 01:57:14 -04:00
joshpatra f96fd4ac14 feat: flash indicator, alongisde the hover control indicator, autohides one when the other appears 2026-03-28 01:33:14 -04:00
joshpatra b96d1a62ec Fix YouTube hover controls & improve nudge indicator UX 2026-03-28 01:21:35 -04:00
joshpatra ab85de0a0f fix: separate Speeder from yt autohide, ignore temp folder with magnus fork to reduce size, update build.py 2026-03-26 18:43:34 -04:00
joshpatra 64f30a04c0 chore: version bump 2026-03-26 13:53:43 -04:00
joshpatra 303864e37b feat(nudge): add per-tab toggle, status badge, and cpu tuning 2026-03-26 13:53:13 -04:00
joshpatra b1c7cb6741 fix(controller): reveal hover controls from the visible pill 2026-03-26 13:11:01 -04:00
joshpatra f8e846ab0c chore: remove __pycache__ from index and gitignore it 2026-03-23 19:44:03 -04:00
joshpatra c6bb82894e Merge pull request #4 from Gitoffthelawn/patch-11
Improve usability, improve accuracy, fix links
2026-03-23 19:39:49 -04:00
Gitoffthelawn 1fc6ab278b Improve usability, improve accuracy, fix links 2026-03-23 12:41:13 -07:00
joshpatra f2c128094e Merge branch 'firefox-port' of github.com:SoPat712/videospeed into firefox-port 2026-03-23 13:23:04 -04:00
joshpatra f34ad12b88 feat: Changed name to Speeder 2026-03-23 13:23:00 -04:00
joshpatra c309fbb743 Update funding sources in FUNDING.yml 2026-03-23 12:57:32 -04:00
joshpatra 6765a6e131 fix(z-index): accidentally left the z-index at 99999, meaning it was showing above all elements on the page 2026-03-23 02:24:44 -04:00
joshpatra a37054efe1 fix: whoops, committed the original 2026-03-21 11:26:42 -04:00
joshpatra f5692e659c fix(detection+reliability): better at recognizing oddly sourced videos, better at not losing track of its speed, better at hiding properly, redid keyboard shortcut mechanism for more stability, added a version number to the settings and menu, hopefully fixed bugs surrounding skipping/pausing resetting the speed 2026-03-21 11:25:56 -04:00
joshpatra ef86a70ca5 general performance updates 2025-11-25 10:44:52 -05:00
joshpatra 5009e83f62 updates for gpu usage 2025-11-19 14:11:55 -05:00
joshpatra 1f8cb4411e Merge branch 'firefox-port' of github.com:SoPat712/videospeed into firefox-port 2025-09-25 18:12:04 -04:00
joshpatra 05a8adef80 gitignore update 2025-09-25 18:12:01 -04:00
joshpatra 4e772cc9e1 Update README.md 2025-07-22 13:36:18 -04:00
joshpatra a10a429aa9 Create LICENSE 2025-07-22 13:35:48 -04:00
joshpatra 01b9b576eb dark mode 2025-07-22 13:19:14 -04:00
joshpatra 893c811802 CPU usage fix since nudging didn't stop properly 2025-07-22 12:17:54 -04:00
joshpatra 3fed3b425e add feature in popup to force search for videos, on websites that it doesn't show up on 2025-07-18 18:00:06 -04:00
19 changed files with 6174 additions and 1188 deletions
+15
View File
@@ -0,0 +1,15 @@
# These are supported funding model platforms
github: [SoPat712]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: joshpatra
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
polar: # Replace with a single Polar username
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
thanks_dev: # Replace with a single thanks.dev username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+71
View File
@@ -0,0 +1,71 @@
name: Build & Release Firefox Addon
on:
push:
tags:
- "v*"
branches:
- dev
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install deps
run: npm install -g web-ext
- name: Lint
run: web-ext lint
# Beta tag (v*-beta) → Sign as unlisted on AMO, attach signed XPI to GitHub Prerelease
# Firefox blocks all unsigned XPIs, even for self-hosted installs — unlisted signing is required
- name: Sign XPI via AMO (unlisted, beta)
if: contains(github.ref_name, '-beta')
run: |
web-ext sign \
--api-key ${{ secrets.FIREFOX_API_KEY }} \
--api-secret ${{ secrets.FIREFOX_API_SECRET }} \
--source-dir . \
--artifacts-dir web-ext-artifacts \
--channel unlisted
- name: Get signed XPI path (beta)
if: contains(github.ref_name, '-beta')
id: xpi
run: |
FILE=$(ls web-ext-artifacts/*.xpi | head -n 1)
XPI="web-ext-artifacts/speeder-${{ github.ref_name }}.xpi"
mv "$FILE" "$XPI"
echo "file=$XPI" >> $GITHUB_OUTPUT
- name: Create GitHub Prerelease (beta)
if: contains(github.ref_name, '-beta')
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ github.ref_name }}
name: Beta ${{ github.ref_name }}
files: ${{ steps.xpi.outputs.file }}
prerelease: true
body: |
Beta build — signed for self-hosted manual installation.
### Installation Instructions
1. Click the `.xpi` file below
2. Click "Continue to Installation"
3. Click "Add"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Stable tag (v* without -beta) → Sign & submit to public AMO listing
- name: Sign & Submit to AMO (stable)
if: startsWith(github.ref, 'refs/tags/') && !contains(github.ref_name, '-beta')
run: |
web-ext sign \
--api-key ${{ secrets.FIREFOX_API_KEY }} \
--api-secret ${{ secrets.FIREFOX_API_SECRET }} \
--source-dir . \
--artifacts-dir web-ext-artifacts \
--channel listed
+4
View File
@@ -1,6 +1,10 @@
.DS_Store
.vscode/
local
# IntelliJ IDEA
*.xpi
.idea/
node_modules
__pycache__/
temp/
+3
View File
@@ -0,0 +1,3 @@
{
"kiroAgent.configureMCP": "Disabled"
}
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+13 -15
View File
@@ -1,5 +1,5 @@
[![Add to Firefox](https://img.shields.io/badge/Add%20to-Firefox-orange?logo=firefox&logoColor=white)](https://addons.mozilla.org/en-US/firefox/addon/video-speed-controller-v1/)
# Available for Firefox
[![Add to Firefox](https://img.shields.io/badge/Add%20to-Firefox-orange?logo=firefox&logoColor=white)](https://addons.mozilla.org//firefox/addon/speeder/)
# The science of accelerated playback
@@ -7,19 +7,19 @@
**TL;DR: faster playback translates to better engagement and retention.**
Average adult reads prose text at
[250 to 300 words per minute](http://www.paperbecause.com/PIOP/files/f7/f7bb6bc5-2c4a-466f-9ae7-b483a2c0dca4.pdf)
[250 to 300 words per minute](https://web.archive.org/web/20220325065025/https://www.domtar.com/en/resources/paper-advocacy/paperbecause)
(wpm). By contrast, the average rate of speech for English speakers is ~150 wpm,
with slide presentations often closer to 100 wpm. As a result, when given the
choice, many viewers
[speed up video playback to ~1.3\~1.5 its recorded rate](http://research.microsoft.com/en-us/um/redmond/groups/coet/compression/chi99/paper.pdf)
[speed up video playback to ~1.3\~1.5 its recorded rate](https://research.microsoft.com/en-us/um/redmond/groups/coet/compression/chi99/paper.pdf)
to compensate for the difference.
Many viewers report that
[accelerated viewing keeps their attention longer](http://www.enounce.com/docs/BYUPaper020319.pdf):
[accelerated viewing keeps their attention longer](https://www.enounce.com/docs/BYUPaper020319.pdf):
faster delivery keeps the viewer more engaged with the content. In fact, with a
little training many end up watching videos at 2x+ the recorded speed. Some
studies report that after being exposed to accelerated playback,
[listeners become uncomfortable](http://alumni.media.mit.edu/~barons/html/avios92.html#beasleyalteredspeech)
[listeners become uncomfortable](https://web.archive.org/web/20230912173120/http://alumni.media.mit.edu/~barons/html/avios92.html)
if they are forced to return to normal rate of presentation.
## Faster HTML5 Video
@@ -36,7 +36,7 @@ last point to listen to it a few more times.
#### *Install [Chrome](https://chrome.google.com/webstore/detail/video-speed-controller/nffaoalbilbmmfgbnbgppjihopabppdk) or [Firefox](https://addons.mozilla.org/en-us/firefox/addon/videospeed/) Extension*
\*\* Once the extension is installed simply navigate to any page that offers
HTML5 video ([example](http://www.youtube.com/watch?v=E9FxNzv1Tr8)), and you'll
HTML5 video ([example](https://www.youtube.com/watch?v=E9FxNzv1Tr8)), and you'll
see a speed indicator in top left corner. Hover over the indicator to reveal the
controls to accelerate, slowdown, and quickly rewind or advance the video. Or,
even better, simply use your keyboard:
@@ -74,14 +74,12 @@ and inspect the menu: if it mentions flash, then that's the issue. That said,
most sites will fallback to HTML5 if they detect that Flash is not available.
You can try manually disabling Flash from the browser.
**What is this fork of `igrigorik/videospeed` all about?** This fork of the
[`igrigorik/videospeed`](https://github.com/igrigorik/videospeed) repository
is a port of [`igrigorik`](https://github.com/igrigorik)'s videospeed Chrome
add-on for Firefox. This fork modifies the Chrome add-on code so that it works
in Firefox. This repo is the code behind the [Firefox Extension](https://addons.mozilla.org/en-US/firefox/addon/video-speed-controller-v1/)
whereas the [`igrigorik/videospeed`](https://github.com/igrigorik/videospeed)
repository contains the code behind the [Chrome Extension](https://chrome.google.com/webstore/detail/video-speed-controller/nffaoalbilbmmfgbnbgppjihopabppdk).
**What is this fork all about?** This is a fork of
[CodeBicycle's Video Speed Controller extension for Firefox](https://github.com/codebicycle/videospeed)
which is a fork of [Igrigorik's Video Speed Controller extension for Chromium](https://github.com/igrigorik/videospeed).
The goal of this fork is fix bugs in the upstream code as well as add new features.
### License
(MIT License) - Copyright (c) 2025 Josh Patra
(GPLv3) - Copyright (c) 2025 Josh Patra
+5
View File
@@ -0,0 +1,5 @@
chrome.runtime.onMessage.addListener(function (request) {
if (request.action === "openOptions") {
chrome.tabs.create({ url: chrome.runtime.getURL("options.html") });
}
});
+59 -20
View File
@@ -1,4 +1,5 @@
import glob
import fnmatch
import os
import re
import shutil
@@ -7,6 +8,32 @@ import zipfile
SCRIPT_NAME = os.path.basename(__file__)
TARGET_FILE = "manifest.json"
DEFAULT_EXCLUDE_FILES = {".DS_Store"}
DEFAULT_EXCLUDE_DIRS = {"__pycache__", "temp"}
DEFAULT_EXCLUDE_PATTERNS = {"._*", "*.pyc"}
def should_exclude(rel_path, exclude_files, exclude_dirs):
rel_path = os.path.normpath(rel_path)
path_parts = rel_path.split(os.sep)
file_name = path_parts[-1]
if file_name in DEFAULT_EXCLUDE_FILES or rel_path in DEFAULT_EXCLUDE_FILES:
return True
if any(part in DEFAULT_EXCLUDE_DIRS for part in path_parts):
return True
if file_name in exclude_files or rel_path in exclude_files:
return True
if any(part in exclude_dirs for part in path_parts):
return True
if any(fnmatch.fnmatch(file_name, pattern) for pattern in DEFAULT_EXCLUDE_PATTERNS):
return True
return False
def zip_folder(output_name, folder, exclude_files, exclude_dirs):
@@ -15,15 +42,15 @@ def zip_folder(output_name, folder, exclude_files, exclude_dirs):
dirs[:] = [
d
for d in dirs
if os.path.relpath(os.path.join(root, d), folder) not in exclude_dirs
if not should_exclude(
os.path.relpath(os.path.join(root, d), folder),
exclude_files,
exclude_dirs,
)
]
for file in files:
rel_path = os.path.relpath(os.path.join(root, file), folder)
if (
file in exclude_files
or rel_path in exclude_files
or any(rel_path.startswith(ed + os.sep) for ed in exclude_dirs)
):
if should_exclude(rel_path, exclude_files, exclude_dirs):
continue
zipf.write(os.path.join(root, file), arcname=rel_path)
@@ -63,37 +90,49 @@ def main():
except Exception as e:
print(f"⚠️ Failed to remove {f}: {e}")
# Read current version from manifest.json
current_dir = os.getcwd()
manifest_path = os.path.join(current_dir, TARGET_FILE)
current_version = "unknown"
if os.path.exists(manifest_path):
with open(manifest_path, "r", encoding="utf-8") as f:
for line in f:
match = re.match(r'\s*"version":\s*"([^"]+)"', line)
if match:
current_version = match.group(1)
break
print(f"📦 Current version: {current_version}")
base_version = input("Enter the new base version (e.g., 2.0.1): ").strip()
if not base_version:
print("❌ No version entered. Exiting.")
return
firefox_version = f"{base_version}.0"
current_dir = os.getcwd()
manifest_path = os.path.join(current_dir, TARGET_FILE)
github_version = f"{base_version}.0"
# Step 1: Update manifest.json on disk to base_version
# Step 1: Update manifest.json on disk to base_version (for Firefox)
if os.path.exists(manifest_path):
update_version_line(manifest_path, base_version)
else:
print(f"{TARGET_FILE} not found. Aborting.")
return
# Step 2: Create videospeed-github.xpi (exclude script, .git, AND videospeed-github.xpi itself)
exclude_files = [SCRIPT_NAME, "videospeed-github.xpi"]
# Step 2: Create videospeed-firefox.xpi (exclude script, .git, AND videospeed-firefox.xpi itself)
exclude_files = [SCRIPT_NAME, "videospeed-firefox.xpi"]
exclude_dirs = [".git"]
zip_folder("videospeed-github.xpi", current_dir, exclude_files, exclude_dirs)
print("✅ Created videospeed-github.xpi")
zip_folder("videospeed-firefox.xpi", current_dir, exclude_files, exclude_dirs)
print("✅ Created videospeed-firefox.xpi")
# Step 3: Re-scan for .xpi files after GitHub archive creation, exclude them for Firefox zip
# Step 3: Re-scan for .xpi files after Firefox archive creation, exclude them for GitHub zip
current_xpi_files = set(glob.glob("*.xpi"))
exclude_temp_files = current_xpi_files.union({SCRIPT_NAME})
exclude_temp_dirs = set(exclude_dirs)
# Step 4: Create videospeed-firefox.xpi from temp folder with version bumped to .0
# Step 4: Create videospeed-github.xpi from temp folder with version bumped to .0
with tempfile.TemporaryDirectory() as temp_dir:
for item in os.listdir(current_dir):
if item in exclude_temp_files or item in exclude_temp_dirs:
if should_exclude(item, exclude_temp_files, exclude_temp_dirs):
continue
src = os.path.join(current_dir, item)
dst = os.path.join(temp_dir, item)
@@ -104,14 +143,14 @@ def main():
temp_manifest = os.path.join(temp_dir, TARGET_FILE)
if os.path.exists(temp_manifest):
update_version_line(temp_manifest, firefox_version)
update_version_line(temp_manifest, github_version)
else:
print(f"⚠️ {TARGET_FILE} not found in temp folder.")
zip_folder(
"videospeed-firefox.xpi", temp_dir, exclude_files=[], exclude_dirs=[]
"videospeed-github.xpi", temp_dir, exclude_files=[], exclude_dirs=[]
)
print("✅ Created videospeed-firefox.xpi")
print("✅ Created videospeed-github.xpi")
if __name__ == "__main__":
+128
View File
@@ -0,0 +1,128 @@
// Import/Export functionality for Video Speed Controller settings
function generateBackupFilename() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, "0");
const day = String(now.getDate()).padStart(2, "0");
const hours = String(now.getHours()).padStart(2, "0");
const minutes = String(now.getMinutes()).padStart(2, "0");
const seconds = String(now.getSeconds()).padStart(2, "0");
return `speeder-backup_${year}-${month}-${day}_${hours}.${minutes}.${seconds}.json`;
}
function exportSettings() {
chrome.storage.sync.get(null, function (storage) {
const backup = {
version: "1.0",
exportDate: new Date().toISOString(),
settings: storage
};
const dataStr = JSON.stringify(backup, null, 2);
const blob = new Blob([dataStr], { type: "application/json" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = generateBackupFilename();
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
showStatus("Settings exported successfully");
});
}
function importSettings() {
const input = document.createElement("input");
input.type = "file";
input.accept = ".json";
input.onchange = function (event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function (e) {
try {
const backup = JSON.parse(e.target.result);
let settingsToImport = null;
// Detect backup format: check for 'settings' wrapper or raw storage keys
if (backup.settings && typeof backup.settings === "object") {
settingsToImport = backup.settings;
} else if (typeof backup === "object" && (backup.keyBindings || backup.rememberSpeed !== undefined)) {
settingsToImport = backup; // Raw storage object
}
if (!settingsToImport) {
showStatus("Error: Invalid backup file format", true);
return;
}
// Import all settings
chrome.storage.sync.clear(function () {
// If clear fails, we still try to set
chrome.storage.sync.set(settingsToImport, function () {
if (chrome.runtime.lastError) {
showStatus("Error: Failed to save imported settings - " + chrome.runtime.lastError.message, true);
return;
}
showStatus("Settings imported successfully. Reloading...");
setTimeout(function () {
if (typeof restore_options === "function") {
restore_options();
} else {
location.reload();
}
}, 500);
});
});
} catch (err) {
showStatus("Error: Failed to parse backup file - " + err.message, true);
}
};
reader.onerror = function () {
showStatus("Error: Failed to read file", true);
};
reader.readAsText(file);
};
input.click();
}
function showStatus(message, isError = false) {
const status = document.getElementById("status");
if (status) {
status.textContent = message;
status.style.color = isError ? "#d32f2f" : "";
setTimeout(function () {
status.textContent = "";
status.style.color = "";
}, 3000);
}
}
// Initialize import/export buttons when DOM is ready
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initImportExport);
} else {
initImportExport();
}
function initImportExport() {
const exportBtn = document.getElementById("exportSettings");
const importBtn = document.getElementById("importSettings");
if (exportBtn) {
exportBtn.addEventListener("click", exportSettings);
}
if (importBtn) {
importBtn.addEventListener("click", importSettings);
}
}
+30 -66
View File
@@ -1,83 +1,47 @@
/* Base styles for the controller wrapper (the shadow host) */
.vsc-controller {
position: absolute !important;
top: 0 !important;
left: 0 !important;
width: 100% !important;
height: 100% !important;
pointer-events: none !important;
z-index: 2147483646 !important;
white-space: normal;
}
/* Use minimal z-index for non-YouTube sites to avoid overlapping modals */
.vsc-controller.vsc-non-youtube {
z-index: 1 !important;
}
.vsc-nosource {
display: none !important;
}
.vsc-hidden {
display: none !important;
}
.vsc-manual {
visibility: visible !important;
opacity: 1 !important;
}
.vsc-controller {
/* In case of pages using `white-space: pre-line` (eg Discord), don't render vsc's whitespace */
white-space: normal;
}
/* Origin specific overrides */
/* YouTube player */
.ytp-hide-info-bar .vsc-controller {
position: relative;
top: 10px;
}
.ytp-autohide .vsc-controller {
/* YouTube auto-hide feature: fade controller with YouTube's controls */
/* When the wrapper has ytp-autohide class, hide it (unless vsc-hidden overrides) */
.vsc-controller.ytp-autohide:not(.vsc-hidden),
.vsc-controller.vsc-idle-hidden:not(.vsc-hidden) {
visibility: hidden;
transition: opacity 0.25s cubic-bezier(0.4, 0, 0.2, 1);
opacity: 0;
}
.ytp-autohide .vcs-show {
visibility: visible;
opacity: 1;
/* Show it temporarily when it has vsc-show class */
.vsc-controller.ytp-autohide.vsc-show:not(.vsc-hidden),
.vsc-controller.vsc-idle-hidden.vsc-show:not(.vsc-hidden),
.vsc-controller.vsc-forced-show:not(.vsc-hidden) {
visibility: visible !important;
opacity: 1 !important;
}
/* YouTube embedded player */
/* e.g. https://www.igvita.com/2012/09/12/web-fonts-performance-making-pretty-fast/ */
.html5-video-player:not(.ytp-hide-info-bar) .vsc-controller {
position: relative;
top: 60px;
}
/* Facebook player */
#facebook .vsc-controller {
position: relative;
top: 40px;
}
/* Google Photos player */
/* Inline preview doesn't have any additional hooks, relying on Aria label */
a[aria-label^="Video"] .vsc-controller {
position: relative;
top: 35px;
}
/* Google Photos full-screen view */
#player .house-brand .vsc-controller {
position: relative;
top: 50px;
}
/* Netflix player */
#netflix-player:not(.player-cinema-mode) .vsc-controller {
position: relative;
top: 85px;
}
/* shift controller on vine.co */
/* e.g. https://vine.co/v/OrJj39YlL57 */
.video-container .vine-video-container .vsc-controller {
margin-left: 40px;
}
/* shift YT 3D controller down */
/* e.g. https://www.youtube.com/watch?v=erftYPflJzQ */
.ytp-webgl-spherical-control {
top: 60px !important;
}
.ytp-fullscreen .ytp-webgl-spherical-control {
top: 100px !important;
}
/* Original overrides removed to avoid interference with the new anchoring system.
The .vsc-controller wrapper now fills the player container exactly,
allowing #controller (inside shadow root) to anchor correctly to all 8 positions. */
/* disable Vimeo video overlay */
div.video-wrapper + div.target {
+2013 -468
View File
@@ -13,25 +13,911 @@ var tc = {
forceLastSavedSpeed: false,
audioBoolean: false,
startHidden: false,
hideWithYouTubeControls: false,
hideWithControls: false,
hideWithControlsTimer: 2.0,
controllerLocation: "top-left",
controllerOpacity: 0.3,
keyBindings: [],
blacklist: `\
www.instagram.com
twitter.com
vine.co
imgur.com
teams.microsoft.com
`.replace(regStrip, ""),
defaultLogLevel: 4,
logLevel: 5, // Set to 5 to see your debug logs
enableSubtitleNudge: true,
subtitleNudgeInterval: 25,
siteRules: [],
controllerButtons: ["rewind", "slower", "faster", "advance", "display"],
defaultLogLevel: 3,
logLevel: 3,
enableSubtitleNudge: true, // Enabled by default, but only activates on YouTube
subtitleNudgeInterval: 50, // Default 50ms balances subtitle tracking with CPU cost
subtitleNudgeAmount: 0.001
},
mediaElements: [],
isNudging: false
isNudging: false,
pendingLastSpeedSave: null,
pendingLastSpeedValue: null,
persistedLastSpeed: 1.0,
activeSiteRule: null
};
var MIN_SPEED = 0.0625;
var MAX_SPEED = 16;
var YT_NATIVE_MIN = 0.25;
var YT_NATIVE_MAX = 2.0;
var YT_NATIVE_STEP = 0.05;
var vscObservedRoots = new WeakSet();
var requestIdle =
typeof window.requestIdleCallback === "function"
? window.requestIdleCallback.bind(window)
: function (callback, options) {
return setTimeout(callback, (options && options.timeout) || 1);
};
var controllerLocations = [
"top-left",
"top-center",
"top-right",
"middle-right",
"bottom-right",
"bottom-center",
"bottom-left",
"middle-left"
];
var defaultControllerLocation = controllerLocations[0];
var controllerLocationStyles = {
"top-left": {
top: "10px",
left: "15px",
transform: "translate(0, 0)"
},
"top-center": {
top: "10px",
left: "50%",
transform: "translate(-50%, 0)"
},
"top-right": {
top: "10px",
left: "calc(100% - 10px)",
transform: "translate(-100%, 0)"
},
"middle-right": {
top: "50%",
left: "calc(100% - 10px)",
transform: "translate(-100%, -50%)"
},
"bottom-right": {
top: "calc(100% - 65px)",
left: "calc(100% - 10px)",
transform: "translate(-100%, -100%)"
},
"bottom-center": {
top: "calc(100% - 65px)",
left: "50%",
transform: "translate(-50%, -100%)"
},
"bottom-left": {
top: "calc(100% - 65px)",
left: "15px",
transform: "translate(0, -100%)"
},
"middle-left": {
top: "50%",
left: "15px",
transform: "translate(0, -50%)"
}
};
var controllerButtonDefs = {
rewind: { label: "\u00AB", className: "rw" },
slower: { label: "\u2212", className: "" },
faster: { label: "+", className: "" },
advance: { label: "\u00BB", className: "rw" },
display: { label: "\u00D7", className: "hideButton" },
reset: { label: "\u21BA", className: "" },
fast: { label: "\u2605", className: "" },
settings: { label: "\u2699", className: "" },
pause: { label: "\u23EF", className: "" },
muted: { label: "M", className: "" },
mark: { label: "\u2691", className: "" },
jump: { label: "\u21E5", className: "" }
};
var keyCodeToEventKey = {
32: " ",
37: "ArrowLeft",
38: "ArrowUp",
39: "ArrowRight",
40: "ArrowDown",
96: "0",
97: "1",
98: "2",
99: "3",
100: "4",
101: "5",
102: "6",
103: "7",
104: "8",
105: "9",
106: "*",
107: "+",
109: "-",
110: ".",
111: "/",
112: "F1",
113: "F2",
114: "F3",
115: "F4",
116: "F5",
117: "F6",
118: "F7",
119: "F8",
120: "F9",
121: "F10",
122: "F11",
123: "F12",
186: ";",
188: "<",
189: "-",
187: "+",
190: ">",
191: "/",
192: "~",
219: "[",
220: "\\",
221: "]",
222: "'",
59: ";",
61: "+",
173: "-"
};
function createDefaultBinding(action, key, keyCode, value) {
return {
action: action,
key: key,
keyCode: keyCode,
value: value,
force: false,
predefined: true
};
}
function defaultKeyBindings(storage) {
return [
createDefaultBinding(
"slower",
"S",
Number(storage.slowerKeyCode) || 83,
Number(storage.speedStep) || 0.1
),
createDefaultBinding(
"faster",
"D",
Number(storage.fasterKeyCode) || 68,
Number(storage.speedStep) || 0.1
),
createDefaultBinding(
"rewind",
"Z",
Number(storage.rewindKeyCode) || 90,
Number(storage.rewindTime) || 10
),
createDefaultBinding(
"advance",
"X",
Number(storage.advanceKeyCode) || 88,
Number(storage.advanceTime) || 10
),
createDefaultBinding(
"reset",
"R",
Number(storage.resetKeyCode) || 82,
1.0
),
createDefaultBinding(
"fast",
"G",
Number(storage.fastKeyCode) || 71,
Number(storage.fastSpeed) || 1.8
),
createDefaultBinding(
"move",
"P",
80,
0
),
createDefaultBinding(
"toggleSubtitleNudge",
"N",
78,
0
)
];
}
function ensureDefaultKeyBinding(action, key, keyCode, value) {
if (tc.settings.keyBindings.some((binding) => binding.action === action)) {
return false;
}
tc.settings.keyBindings.push(
createDefaultBinding(action, key, keyCode, value)
);
return true;
}
function getLegacyKeyCode(binding) {
if (!binding) return null;
if (Number.isInteger(binding.keyCode)) return binding.keyCode;
if (typeof binding.key === "number" && Number.isInteger(binding.key)) {
return binding.key;
}
return null;
}
function normalizeControllerLocation(location) {
if (controllerLocations.includes(location)) return location;
return defaultControllerLocation;
}
function getNextControllerLocation(location) {
var normalizedLocation = normalizeControllerLocation(location);
var currentIndex = controllerLocations.indexOf(normalizedLocation);
return controllerLocations[(currentIndex + 1) % controllerLocations.length];
}
function getControllerElement(videoOrController) {
if (!videoOrController) return null;
if (
videoOrController.shadowRoot &&
typeof videoOrController.shadowRoot.querySelector === "function"
) {
return videoOrController.shadowRoot.querySelector("#controller");
}
if (
videoOrController.div &&
videoOrController.div.shadowRoot &&
typeof videoOrController.div.shadowRoot.querySelector === "function"
) {
return videoOrController.div.shadowRoot.querySelector("#controller");
}
return null;
}
function applyControllerLocationToElement(controller, location) {
if (!controller) return defaultControllerLocation;
var normalizedLocation = normalizeControllerLocation(location);
var styles = controllerLocationStyles[normalizedLocation];
controller.dataset.location = normalizedLocation;
controller.dataset.positionMode = "anchored";
var top = styles.top;
// If in fullscreen, move the controller down to avoid overlapping video titles
if (
document.fullscreenElement ||
document.webkitFullscreenElement ||
document.mozFullScreenElement ||
document.msFullscreenElement
) {
if (normalizedLocation.startsWith("top-")) {
top = "63px";
}
}
controller.style.top = top;
controller.style.left = styles.left;
controller.style.transform = styles.transform;
return normalizedLocation;
}
function applyControllerLocation(videoController, location) {
if (!videoController) return;
var controller = getControllerElement(videoController);
if (!controller) return;
videoController.controllerLocation = applyControllerLocationToElement(
controller,
location
);
}
function clearManualControllerPosition(videoController) {
if (!videoController) return;
applyControllerLocation(
videoController,
videoController.controllerLocation || tc.settings.controllerLocation
);
}
function convertControllerToManualPosition(videoController) {
if (!videoController) return null;
var controller = getControllerElement(videoController);
if (!controller) return null;
controller.dataset.positionMode = "manual";
var offsetParent = controller.offsetParent;
if (offsetParent) {
var controllerRect = controller.getBoundingClientRect();
var offsetParentRect = offsetParent.getBoundingClientRect();
controller.style.setProperty(
"left",
controllerRect.left - offsetParentRect.left + "px",
"important"
);
controller.style.setProperty(
"top",
controllerRect.top - offsetParentRect.top + "px",
"important"
);
} else {
controller.style.setProperty(
"left",
controller.offsetLeft + "px",
"important"
);
controller.style.setProperty(
"top",
controller.offsetTop + "px",
"important"
);
}
controller.style.setProperty("transform", "none", "important");
return controller;
}
function cycleControllerLocation(video) {
if (!video || !video.vsc) return;
video.vsc.controllerLocation = getNextControllerLocation(
video.vsc.controllerLocation || tc.settings.controllerLocation
);
clearManualControllerPosition(video.vsc);
}
function normalizeBindingKey(key) {
if (typeof key !== "string" || key.length === 0) return null;
if (key === "Spacebar") return " ";
if (key === "Esc") return "Escape";
if (key.length === 1 && /[a-z]/i.test(key)) return key.toUpperCase();
return key;
}
function legacyKeyCodeToBinding(keyCode) {
if (!Number.isInteger(keyCode)) return null;
var key = keyCodeToEventKey[keyCode];
if (!key && keyCode >= 48 && keyCode <= 57) {
key = String.fromCharCode(keyCode);
}
if (!key && keyCode >= 65 && keyCode <= 90) {
key = String.fromCharCode(keyCode);
}
return {
key: normalizeBindingKey(key),
keyCode: keyCode,
code: null,
disabled: false
};
}
function normalizeStoredBinding(binding, fallbackKeyCode) {
var fallbackBinding = legacyKeyCodeToBinding(fallbackKeyCode);
if (!binding) return fallbackBinding;
if (
binding.disabled === true ||
(binding.key === null &&
binding.keyCode === null &&
binding.code === null)
) {
return {
action: binding.action,
key: null,
keyCode: null,
code: null,
disabled: true,
value: Number(binding.value),
force: String(binding.force) === "true" ? "true" : "false",
predefined: Boolean(binding.predefined)
};
}
var normalized = {
action: binding.action,
key: null,
keyCode: null,
code:
typeof binding.code === "string" && binding.code.length > 0
? binding.code
: null,
disabled: false,
value: Number(binding.value),
force: String(binding.force) === "true" ? "true" : "false",
predefined: Boolean(binding.predefined)
};
if (typeof binding.key === "string") {
normalized.key = normalizeBindingKey(binding.key);
}
var legacyKeyCode = getLegacyKeyCode(binding);
if (Number.isInteger(legacyKeyCode)) {
var legacyBinding = legacyKeyCodeToBinding(legacyKeyCode);
if (legacyBinding) {
normalized.key = normalized.key || legacyBinding.key;
normalized.keyCode = legacyKeyCode;
}
}
if (Number.isInteger(binding.keyCode)) {
normalized.keyCode = binding.keyCode;
}
if (!normalized.key && fallbackBinding) {
normalized.key = fallbackBinding.key;
if (normalized.keyCode === null) normalized.keyCode = fallbackBinding.keyCode;
}
if (!normalized.key && !normalized.code && normalized.keyCode === null) {
return null;
}
return normalized;
}
function isValidSpeed(speed) {
return !isNaN(speed) && speed >= MIN_SPEED && speed <= MAX_SPEED;
}
function sanitizeSpeed(speed, fallback) {
var numericSpeed = Number(speed);
return isValidSpeed(numericSpeed) ? numericSpeed : fallback;
}
function getVideoSourceKey(video) {
return (video && (video.currentSrc || video.src)) || "unknown_src";
}
function getControllerTargetSpeed(video) {
if (!video || !video.vsc) return null;
return isValidSpeed(video.vsc.targetSpeed) ? video.vsc.targetSpeed : null;
}
function getRememberedSpeed(video) {
var sourceKey = getVideoSourceKey(video);
if (sourceKey !== "unknown_src") {
var videoSpeed = tc.settings.speeds[sourceKey];
if (isValidSpeed(videoSpeed)) return videoSpeed;
}
if (tc.settings.forceLastSavedSpeed && isValidSpeed(tc.settings.lastSpeed)) {
return tc.settings.lastSpeed;
}
if (tc.settings.rememberSpeed && isValidSpeed(tc.settings.lastSpeed)) {
return tc.settings.lastSpeed;
}
return null;
}
function getDesiredSpeed(video) {
return getControllerTargetSpeed(video) || getRememberedSpeed(video) || 1.0;
}
function isOnYouTube() {
return (
location.hostname.includes("youtube.com") ||
location.hostname.includes("youtube-nocookie.com")
);
}
function isYouTubeNativeSpeedRange(speed) {
if (speed < YT_NATIVE_MIN || speed > YT_NATIVE_MAX) return false;
// Check if speed is a multiple of 0.05 (with floating point tolerance)
var remainder = Math.abs((speed * 100) % (YT_NATIVE_STEP * 100));
return remainder < 0.01 || remainder > (YT_NATIVE_STEP * 100 - 0.01);
}
function tryYouTubeNativeSpeed(video, speed) {
if (!isOnYouTube() || !isYouTubeNativeSpeedRange(speed)) return false;
try {
// YouTube's movie_player element exposes setPlaybackRate() but it's a
// page-level JS method, not a native DOM method. Content scripts can't
// see it directly. In Firefox, wrappedJSObject gives access to the
// page's JS context.
var playerEl =
video.closest(".html5-video-player") ||
document.getElementById("movie_player");
if (!playerEl) return false;
// Try wrappedJSObject first (Firefox content script → page context)
var player = playerEl.wrappedJSObject || playerEl;
if (typeof player.setPlaybackRate === "function") {
player.setPlaybackRate(speed);
// Verify YouTube actually accepted the speed (it may silently clamp)
var actualSpeed = video.playbackRate;
if (Math.abs(actualSpeed - speed) > 0.01) {
log("YouTube clamped speed to " + actualSpeed + ", falling back", 4);
return false;
}
log("Used YouTube native setPlaybackRate: " + speed, 4);
return true;
}
} catch (e) {
log("YouTube native speed failed: " + e.message, 3);
}
return false;
}
function isSubtitleNudgeSupported(video) {
return Boolean(video);
}
function isSubtitleNudgeEnabledForVideo(video) {
if (!video || !video.vsc) return tc.settings.enableSubtitleNudge;
if (typeof video.vsc.subtitleNudgeEnabledOverride === "boolean") {
return video.vsc.subtitleNudgeEnabledOverride;
}
return tc.settings.enableSubtitleNudge;
}
function setSubtitleNudgeEnabledForVideo(video, enabled) {
if (!video || !video.vsc) return false;
var normalizedEnabled = Boolean(enabled);
video.vsc.subtitleNudgeEnabledOverride = normalizedEnabled;
if (!normalizedEnabled) {
video.vsc.stopSubtitleNudge();
} else if (!video.paused && video.playbackRate !== 1.0) {
video.vsc.startSubtitleNudge();
}
updateSubtitleNudgeIndicator(video);
// Briefly flash the standalone indicator next to the speed text
var flashEl = video.vsc.nudgeFlashIndicator;
if (flashEl) {
flashEl.classList.add("visible");
clearTimeout(flashEl._flashTimer);
flashEl._flashTimer = setTimeout(function () {
flashEl.classList.remove("visible");
}, 1500);
}
return normalizedEnabled;
}
function updateSubtitleNudgeIndicator(video) {
if (!video || !video.vsc) return;
var isEnabled = isSubtitleNudgeEnabledForVideo(video);
var label = isEnabled ? "✓" : "×";
var title = isEnabled ? "Subtitle nudge enabled" : "Subtitle nudge disabled";
var indicator = video.vsc.subtitleNudgeIndicator;
if (indicator) {
indicator.textContent = label;
indicator.dataset.enabled = isEnabled ? "true" : "false";
indicator.dataset.supported = "true";
indicator.title = title;
indicator.setAttribute("aria-label", title);
}
var flashEl = video.vsc.nudgeFlashIndicator;
if (flashEl) {
flashEl.textContent = label;
flashEl.dataset.enabled = isEnabled ? "true" : "false";
flashEl.dataset.supported = "true";
}
}
function schedulePersistLastSpeed(speed) {
if (!isValidSpeed(speed)) return;
tc.pendingLastSpeedValue = speed;
if (tc.pendingLastSpeedSave !== null) return;
tc.pendingLastSpeedSave = setTimeout(function () {
var speedToPersist = tc.pendingLastSpeedValue;
tc.pendingLastSpeedSave = null;
if (!isValidSpeed(speedToPersist) || tc.persistedLastSpeed === speedToPersist) {
return;
}
chrome.storage.sync.set({ lastSpeed: speedToPersist }, function () { });
tc.persistedLastSpeed = speedToPersist;
}, 250);
}
function suppressNextNudgeRateChanges(controller, count) {
if (!controller) return;
controller.suppressedRateChangeCount =
(controller.suppressedRateChangeCount || 0) + (count || 2);
controller.suppressedRateChangeUntil =
Date.now() + Math.max(250, tc.settings.subtitleNudgeInterval * 4);
}
function shouldIgnoreSuppressedRateChange(video) {
if (!video || !video.vsc) return false;
var controller = video.vsc;
if (
controller.suppressedRateChangeCount > 0 &&
controller.suppressedRateChangeUntil >= Date.now()
) {
controller.suppressedRateChangeCount -= 1;
return true;
}
if (controller.suppressedRateChangeUntil < Date.now()) {
controller.suppressedRateChangeCount = 0;
}
return false;
}
function resolveTargetSpeed(video) {
return getDesiredSpeed(video);
}
function extendSpeedRestoreWindow(video, duration) {
if (!video || !video.vsc) return;
var restoreDuration = Number(duration) || 1500;
var restoreUntil = Date.now() + restoreDuration;
var currentUntil = Number(video.vsc.speedRestoreUntil) || 0;
video.vsc.speedRestoreUntil = Math.max(currentUntil, restoreUntil);
}
function scheduleSpeedRestore(video, desiredSpeed, reason) {
if (!video || !video.vsc || !isValidSpeed(desiredSpeed)) return;
if (video.vsc.restoreSpeedTimer) {
clearTimeout(video.vsc.restoreSpeedTimer);
}
video.vsc.restoreSpeedTimer = setTimeout(function () {
if (!video.vsc) return;
if (Math.abs(video.playbackRate - desiredSpeed) > 0.01) {
log(
`Restoring playbackRate to ${desiredSpeed.toFixed(2)} after ${reason}`,
4
);
setSpeed(video, desiredSpeed, false, false);
}
if (video.vsc) {
video.vsc.restoreSpeedTimer = null;
}
}, 0);
}
function rememberPendingRateChange(video, speed) {
if (!video || !video.vsc || !isValidSpeed(speed)) return;
video.vsc.pendingRateChange = {
speed: Number(speed),
expiresAt: Date.now() + 1000
};
}
function takePendingRateChange(video, currentSpeed) {
if (!video || !video.vsc || !video.vsc.pendingRateChange) return null;
var pendingRateChange = video.vsc.pendingRateChange;
if (
!isValidSpeed(pendingRateChange.speed) ||
pendingRateChange.expiresAt <= Date.now()
) {
video.vsc.pendingRateChange = null;
return null;
}
if (Math.abs(Number(pendingRateChange.speed) - currentSpeed) > 0.01) {
return null;
}
video.vsc.pendingRateChange = null;
return pendingRateChange;
}
function matchesKeyBinding(binding, event) {
if (!binding || binding.disabled) return false;
var normalizedEventKey = normalizeBindingKey(event.key);
if (binding.key && normalizedEventKey) {
return binding.key === normalizedEventKey;
}
if (binding.code && event.code) {
return binding.code === event.code;
}
var legacyKeyCode = getLegacyKeyCode(binding);
return Number.isInteger(legacyKeyCode) && legacyKeyCode === event.keyCode;
}
function mediaSelector() {
return tc.settings.audioBoolean ? "video,audio" : "video";
}
function isMediaElement(node) {
return (
node &&
node.nodeType === Node.ELEMENT_NODE &&
(node.nodeName === "VIDEO" ||
(node.nodeName === "AUDIO" && tc.settings.audioBoolean))
);
}
function hasUsableMediaSource(node) {
if (!isMediaElement(node) || !node.isConnected) return false;
if (node.currentSrc || node.src || node.srcObject) return true;
if (typeof node.readyState === "number" && node.readyState > 0) return true;
if (
typeof node.networkState === "number" &&
typeof HTMLMediaElement !== "undefined" &&
(node.networkState === HTMLMediaElement.NETWORK_IDLE ||
node.networkState === HTMLMediaElement.NETWORK_LOADING)
) {
return true;
}
if (node.querySelectorAll) {
return Array.from(node.querySelectorAll("source[src]")).some(function (
source
) {
var src = source.getAttribute("src");
return typeof src === "string" && src.trim().length > 0;
});
}
return false;
}
function ensureController(node, parent) {
if (!isMediaElement(node) || node.vsc) return node && node.vsc;
if (!hasUsableMediaSource(node)) {
log(
`Deferring controller creation for ${node.tagName}: no usable source yet`,
5
);
return null;
}
log(
`Creating controller for ${node.tagName}: ${node.src || node.currentSrc || "no src"}`,
4
);
node.vsc = new tc.videoController(
node,
parent || node.parentElement || node.parentNode
);
return node.vsc;
}
function removeController(node) {
if (node && node.vsc) node.vsc.remove();
}
function scanNodeForMedia(node, parent, added) {
if (!node || typeof node === "function") return;
if (node.nodeType === Node.DOCUMENT_NODE) {
scanNodeForMedia(node.body || node.documentElement, node.body, added);
return;
}
if (
node.nodeType !== Node.ELEMENT_NODE &&
node.nodeType !== Node.DOCUMENT_FRAGMENT_NODE
) {
return;
}
var ownerDocument = node.ownerDocument || document;
if (!added && ownerDocument.body && ownerDocument.body.contains(node)) return;
// Check if the node itself is a media element
if (isMediaElement(node)) {
if (added) ensureController(node, parent);
else removeController(node);
}
// Use querySelectorAll instead of recursive child walking — the browser's
// native selector engine is orders of magnitude faster than JS recursion.
if (typeof node.querySelectorAll === "function") {
var selector = mediaSelector();
try {
var mediaElements = node.querySelectorAll(selector);
for (var i = 0; i < mediaElements.length; i++) {
var el = mediaElements[i];
if (added) ensureController(el, el.parentNode || parent);
else removeController(el);
}
} catch (e) {
// querySelectorAll may throw on detached or unusual nodes
}
}
// Still need to observe shadow roots for media inside web components
if (node.shadowRoot) {
observeRoot(node.shadowRoot);
}
}
function getScanNodeForRoot(root) {
if (!root) return null;
if (root.nodeType === Node.DOCUMENT_NODE) {
return root.body || root.documentElement;
}
return root;
}
function rootMayContainMedia(root) {
if (!root) return false;
if (root.nodeType === Node.DOCUMENT_NODE) return true;
if (typeof root.querySelector !== "function") return true;
try {
return Boolean(root.querySelector(mediaSelector()));
} catch (error) {
return true;
}
}
function scanRootForMedia(root) {
var scanRoot = getScanNodeForRoot(root);
if (!scanRoot) return;
scanNodeForMedia(scanRoot, root.host || scanRoot.parentNode || scanRoot, true);
if (root.nodeType === Node.DOCUMENT_NODE) {
attachIframeListeners(root);
}
}
function observeRoot(root) {
if (!root || vscObservedRoots.has(root)) return;
vscObservedRoots.add(root);
setupListener(root);
attachMutationObserver(root);
attachMediaDetectionListeners(root);
if (rootMayContainMedia(root)) {
scanRootForMedia(root);
}
}
function patchAttachShadow() {
if (
window.vscAttachShadowPatched ||
typeof Element === "undefined" ||
typeof Element.prototype.attachShadow !== "function"
) {
return;
}
var originalAttachShadow = Element.prototype.attachShadow;
Element.prototype.attachShadow = function () {
var shadowRoot = originalAttachShadow.apply(this, arguments);
try {
if (shadowRoot) {
observeRoot(shadowRoot);
}
} catch (error) {
log(`Unable to observe shadow root: ${error.message}`, 3);
}
return shadowRoot;
};
window.vscAttachShadowPatched = true;
}
/* Log levels */
function log(message, level) {
verbosity = tc.settings.logLevel;
@@ -50,51 +936,16 @@ function log(message, level) {
}
chrome.storage.sync.get(tc.settings, function (storage) {
// Original initialization from your code
tc.settings.keyBindings = storage.keyBindings;
if (storage.keyBindings.length == 0) {
tc.settings.keyBindings.push({
action: "slower",
key: Number(storage.slowerKeyCode) || 83,
value: Number(storage.speedStep) || 0.1,
force: false,
predefined: true
});
tc.settings.keyBindings.push({
action: "faster",
key: Number(storage.fasterKeyCode) || 68,
value: Number(storage.speedStep) || 0.1,
force: false,
predefined: true
});
tc.settings.keyBindings.push({
action: "rewind",
key: Number(storage.rewindKeyCode) || 90,
value: Number(storage.rewindTime) || 10,
force: false,
predefined: true
});
tc.settings.keyBindings.push({
action: "advance",
key: Number(storage.advanceKeyCode) || 88,
value: Number(storage.advanceTime) || 10,
force: false,
predefined: true
});
tc.settings.keyBindings.push({
action: "reset",
key: Number(storage.resetKeyCode) || 82,
value: 1.0,
force: false,
predefined: true
});
tc.settings.keyBindings.push({
action: "fast",
key: Number(storage.fastKeyCode) || 71,
value: Number(storage.fastSpeed) || 1.8,
force: false,
predefined: true
});
var storedBindings = Array.isArray(storage.keyBindings)
? storage.keyBindings
: [];
tc.settings.keyBindings = storedBindings
.map((binding) => normalizeStoredBinding(binding))
.filter(Boolean);
if (tc.settings.keyBindings.length === 0) {
tc.settings.keyBindings = defaultKeyBindings(storage);
tc.settings.version = "0.5.3";
chrome.storage.sync.set({
keyBindings: tc.settings.keyBindings,
@@ -105,37 +956,136 @@ chrome.storage.sync.get(tc.settings, function (storage) {
audioBoolean: tc.settings.audioBoolean,
startHidden: tc.settings.startHidden,
enabled: tc.settings.enabled,
controllerOpacity: tc.settings.controllerOpacity,
blacklist: tc.settings.blacklist.replace(regStrip, "")
controllerLocation: tc.settings.controllerLocation,
controllerOpacity: tc.settings.controllerOpacity
});
}
tc.settings.lastSpeed = Number(storage.lastSpeed);
if (!isValidSpeed(tc.settings.lastSpeed) && tc.settings.lastSpeed !== 1.0) {
log(`Invalid lastSpeed detected: ${storage.lastSpeed}, resetting to 1.0`, 3);
tc.settings.lastSpeed = 1.0;
tc.persistedLastSpeed = 1.0;
chrome.storage.sync.set({ lastSpeed: 1.0 });
} else if (!isValidSpeed(tc.settings.lastSpeed)) {
tc.settings.lastSpeed = 1.0;
}
tc.persistedLastSpeed = tc.settings.lastSpeed;
tc.settings.displayKeyCode = Number(storage.displayKeyCode);
tc.settings.rememberSpeed = Boolean(storage.rememberSpeed);
tc.settings.forceLastSavedSpeed = Boolean(storage.forceLastSavedSpeed);
tc.settings.audioBoolean = Boolean(storage.audioBoolean);
tc.settings.enabled = Boolean(storage.enabled);
tc.settings.startHidden = Boolean(storage.startHidden);
tc.settings.hideWithControls =
typeof storage.hideWithControls !== "undefined"
? Boolean(storage.hideWithControls)
: Boolean(storage.hideWithYouTubeControls);
tc.settings.hideWithControlsTimer =
Math.min(15, Math.max(0.1, Number(storage.hideWithControlsTimer) || 2.0));
tc.settings.hideWithYouTubeControls = tc.settings.hideWithControls;
tc.settings.controllerLocation = normalizeControllerLocation(
storage.controllerLocation
);
tc.settings.controllerOpacity = Number(storage.controllerOpacity);
tc.settings.blacklist = String(storage.blacklist);
tc.settings.siteRules = Array.isArray(storage.siteRules)
? storage.siteRules
: [];
tc.settings.controllerButtons = Array.isArray(storage.controllerButtons)
? storage.controllerButtons
: tc.settings.controllerButtons;
// Migrate legacy blacklist if present
if (storage.blacklist && typeof storage.blacklist === "string" && tc.settings.siteRules.length === 0) {
var lines = storage.blacklist.split("\n");
lines.forEach((line) => {
var pattern = line.replace(regStrip, "");
if (pattern.length > 0) {
tc.settings.siteRules.push({
pattern: pattern,
disableExtension: true
});
}
});
if (tc.settings.siteRules.length > 0) {
chrome.storage.sync.set({ siteRules: tc.settings.siteRules });
chrome.storage.sync.remove(["blacklist"]);
log("Migrated legacy blacklist to site rules", 4);
}
}
tc.settings.enableSubtitleNudge =
typeof storage.enableSubtitleNudge !== "undefined"
? Boolean(storage.enableSubtitleNudge)
: tc.settings.enableSubtitleNudge;
tc.settings.subtitleNudgeInterval =
Number(storage.subtitleNudgeInterval) || 25;
tc.settings.subtitleNudgeInterval = Math.min(
1000,
Math.max(10, Number(storage.subtitleNudgeInterval) || 50)
);
tc.settings.subtitleNudgeAmount =
Number(storage.subtitleNudgeAmount) || tc.settings.subtitleNudgeAmount;
if (
tc.settings.keyBindings.filter((x) => x.action == "display").length == 0
) {
tc.settings.keyBindings.push({
action: "display",
key: Number(storage.displayKeyCode) || 86,
value: 0,
force: false,
predefined: true
});
var addedDefaultBinding = false;
addedDefaultBinding =
ensureDefaultKeyBinding(
"display",
"V",
Number(storage.displayKeyCode) || 86,
0
) || addedDefaultBinding;
addedDefaultBinding =
ensureDefaultKeyBinding("move", "P", 80, 0) || addedDefaultBinding;
addedDefaultBinding =
ensureDefaultKeyBinding("toggleSubtitleNudge", "N", 78, 0) ||
addedDefaultBinding;
if (addedDefaultBinding) {
chrome.storage.sync.set({ keyBindings: tc.settings.keyBindings });
}
patchAttachShadow();
// Add a listener for messages from the popup.
// We use a global flag to ensure the listener is only attached once.
if (!window.vscMessageListener) {
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.action === "rescan_page") {
log("Re-scan command received from popup.", 4);
initializeWhenReady(document, true);
sendResponse({ status: "complete" });
} else if (request.action === "get_speed") {
var speed = 1.0;
if (tc.mediaElements && tc.mediaElements.length > 0) {
for (var i = 0; i < tc.mediaElements.length; i++) {
if (tc.mediaElements[i] && !tc.mediaElements[i].paused) {
speed = tc.mediaElements[i].playbackRate;
break;
}
}
if (speed === 1.0 && tc.mediaElements[0]) {
speed = tc.mediaElements[0].playbackRate;
}
}
sendResponse({ speed: speed });
} else if (request.action === "get_page_context") {
sendResponse({ url: location.href });
} else if (request.action === "run_action") {
var value = request.value;
if (value === undefined || value === null) {
value = getKeyBindings(request.actionName, "value");
}
runAction(request.actionName, value);
var newSpeed = 1.0;
if (tc.mediaElements && tc.mediaElements.length > 0) {
newSpeed = tc.mediaElements[0].playbackRate;
}
sendResponse({ speed: newSpeed });
}
return true;
}
);
// Set the flag to prevent adding the listener again.
window.vscMessageListener = true;
}
initializeWhenReady(document);
});
@@ -152,6 +1102,16 @@ function setKeyBindings(action, value) {
value;
}
function createControllerButton(doc, action, label, className) {
var button = doc.createElement("button");
button.dataset.action = action;
button.textContent = label;
if (className) {
button.className = className;
}
return button;
}
function defineVideoController() {
tc.videoController = function (target, parent) {
if (target.vsc) return target.vsc;
@@ -159,77 +1119,83 @@ function defineVideoController() {
target.vsc = this;
this.video = target;
this.parent = target.parentElement || parent;
this.nudgeIntervalId = null;
this.nudgeAnimationId = null;
this.restoreSpeedTimer = null;
this.pendingRateChange = null;
this.speedRestoreUntil = 0;
this.subtitleNudgeEnabledOverride = null;
this.suppressedRateChangeCount = 0;
this.suppressedRateChangeUntil = 0;
this.visibilityResumeHandler = null;
this.controllerLocation = normalizeControllerLocation(
tc.settings.controllerLocation
);
// Determine what speed to use
let storedSpeed = tc.settings.speeds[target.currentSrc];
if (!tc.settings.rememberSpeed) {
if (!storedSpeed) {
storedSpeed = 1.0;
}
} else {
storedSpeed = tc.settings.lastSpeed;
}
if (tc.settings.forceLastSavedSpeed) {
storedSpeed = tc.settings.lastSpeed;
log(`Creating video controller for ${target.tagName} with src: ${target.src || target.currentSrc || 'none'}`, 4);
let storedSpeed = sanitizeSpeed(resolveTargetSpeed(target), 1.0);
this.targetSpeed = storedSpeed;
if (!tc.settings.rememberSpeed && !tc.settings.forceLastSavedSpeed) {
setKeyBindings("reset", getKeyBindings("fast"));
}
// FIXED: Actually apply the speed to the video element
// Use setSpeed function to properly set the speed with all the necessary logic
setTimeout(() => {
if (this.video && this.video.vsc) {
setSpeed(this.video, storedSpeed, true, false);
}
}, 0);
log("Explicitly setting playbackRate to: " + storedSpeed, 5);
target.playbackRate = storedSpeed;
this.div = this.initializeControls();
// Make the controller visible for 5 seconds on startup
runAction("blink", 5000, null, this.video);
if (!this.div) {
log("ERROR: Failed to create controller div!", 2);
return;
}
log(`Controller created and attached to DOM. Hidden: ${this.div.classList.contains('vsc-hidden')}`, 4);
// Rewritten mediaEventAction to prevent speed reset on pause.
var mediaEventAction = function (event) {
// Handle subtitle nudging based on the event type first.
if (event.type === "play") {
this.startSubtitleNudge();
extendSpeedRestoreWindow(event.target);
// FIXED: Only reapply speed if there's a significant mismatch AND it's a new video
const currentSpeed = event.target.playbackRate;
const videoId =
event.target.currentSrc || event.target.src || "default";
if (!tc.settings.rememberSpeed && !tc.settings.forceLastSavedSpeed) {
setKeyBindings("reset", getKeyBindings("fast"));
}
// Get the expected speed based on settings
let expectedSpeed;
if (tc.settings.forceLastSavedSpeed) {
expectedSpeed = tc.settings.lastSpeed;
var playSpeed = sanitizeSpeed(resolveTargetSpeed(event.target), 1.0);
if (Math.abs(event.target.playbackRate - playSpeed) > 0.01) {
log("Play event: setting playbackRate to: " + playSpeed, 4);
setSpeed(event.target, playSpeed, false, false);
} else if (playSpeed === 1.0 || event.target.paused) {
this.stopSubtitleNudge();
} else {
expectedSpeed = tc.settings.speeds[videoId] || tc.settings.lastSpeed;
this.startSubtitleNudge();
}
// Only reapply speed if:
// 1. The current speed is 1.0 (default) AND we have a stored speed that's different
// 2. OR if forceLastSavedSpeed is enabled and speeds don't match
const shouldReapplySpeed =
(Math.abs(currentSpeed - 1.0) < 0.01 &&
Math.abs(expectedSpeed - 1.0) > 0.01) ||
(tc.settings.forceLastSavedSpeed &&
Math.abs(currentSpeed - expectedSpeed) > 0.01);
if (shouldReapplySpeed) {
setTimeout(() => {
if (event.target.vsc) {
setSpeed(event.target, expectedSpeed, false, false);
}
}, 10);
}
} else if (event.type === "pause" || event.type === "ended") {
} else if (event.type === "pause") {
extendSpeedRestoreWindow(event.target);
this.stopSubtitleNudge();
}
tc.isNudging = false;
} else if (event.type === "seeking") {
extendSpeedRestoreWindow(event.target);
} else if (event.type === "ended") {
this.speedRestoreUntil = 0;
this.stopSubtitleNudge();
tc.isNudging = false;
} else if (event.type === "seeked") {
extendSpeedRestoreWindow(event.target);
var expectedSpeed = sanitizeSpeed(resolveTargetSpeed(event.target), 1.0);
var currentSpeed = event.target.playbackRate;
// For seek events, don't mess with speed
if (event.type === "seeked" && isUserSeek) {
isUserSeek = false;
return;
if (
Math.abs(currentSpeed - expectedSpeed) > 0.01
) {
log(
`Seeked: speed changed from ${expectedSpeed} to ${currentSpeed}, restoring`,
4
);
setSpeed(event.target, expectedSpeed, false, false);
}
if (isUserSeek) {
isUserSeek = false;
}
}
};
@@ -241,6 +1207,10 @@ function defineVideoController() {
"pause",
(this.handlePause = mediaEventAction.bind(this))
);
target.addEventListener(
"seeking",
(this.handleSeeking = mediaEventAction.bind(this))
);
target.addEventListener(
"ended",
(this.handleEnded = mediaEventAction.bind(this))
@@ -250,31 +1220,6 @@ function defineVideoController() {
(this.handleSeek = mediaEventAction.bind(this))
);
// ADDITIONAL FIX: Listen for loadedmetadata to reapply speed when video source changes
target.addEventListener("loadedmetadata", () => {
if (this.video && this.video.vsc) {
const currentSpeed = this.video.playbackRate;
const videoId = this.video.currentSrc || this.video.src || "default";
// Get expected speed
let expectedSpeed;
if (tc.settings.forceLastSavedSpeed) {
expectedSpeed = tc.settings.lastSpeed;
} else {
expectedSpeed = tc.settings.speeds[videoId] || tc.settings.lastSpeed;
}
// Only reapply if current speed is default (1.0) and we have a different stored speed
const shouldReapplySpeed =
Math.abs(currentSpeed - 1.0) < 0.01 &&
Math.abs(expectedSpeed - 1.0) > 0.01;
if (shouldReapplySpeed) {
setSpeed(this.video, expectedSpeed, false, false);
}
}
});
var srcObserver = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (
@@ -282,31 +1227,21 @@ function defineVideoController() {
(mutation.attributeName === "src" ||
mutation.attributeName === "currentSrc")
) {
log("mutation of A/V element", 5);
if (this.div) {
this.stopSubtitleNudge();
if (!mutation.target.src && !mutation.target.currentSrc) {
this.div.classList.add("vsc-nosource");
} else {
this.div.classList.remove("vsc-nosource");
// FIXED: Reapply speed when source changes (like in shorts)
const expectedSpeed = tc.settings.forceLastSavedSpeed
? tc.settings.lastSpeed
: tc.settings.speeds[mutation.target.currentSrc] ||
tc.settings.lastSpeed;
setTimeout(() => {
if (mutation.target.vsc) {
setSpeed(mutation.target, expectedSpeed, false, false);
}
}, 100);
if (!mutation.target.paused) this.startSubtitleNudge();
}
updateSubtitleNudgeIndicator(this.video);
}
}
});
});
this.srcObserver = srcObserver;
srcObserver.observe(target, { attributeFilter: ["src", "currentSrc"] });
if (!target.paused && target.playbackRate !== 1.0)
this.startSubtitleNudge();
@@ -314,93 +1249,361 @@ function defineVideoController() {
tc.videoController.prototype.remove = function () {
this.stopSubtitleNudge();
if (this.youTubeAutoHideObserver) {
this.youTubeAutoHideObserver.disconnect();
this.youTubeAutoHideObserver = null;
}
if (this.youTubeAutoHideCleanup) {
this.youTubeAutoHideCleanup();
this.youTubeAutoHideCleanup = null;
}
if (this.genericAutoHideCleanup) {
this.genericAutoHideCleanup();
this.genericAutoHideCleanup = null;
}
if (this.div) this.div.remove();
if (this.restoreSpeedTimer) clearTimeout(this.restoreSpeedTimer);
if (this.video) {
this.video.removeEventListener("play", this.handlePlay);
this.video.removeEventListener("pause", this.handlePause);
this.video.removeEventListener("seeking", this.handleSeeking);
this.video.removeEventListener("ended", this.handleEnded);
this.video.removeEventListener("seeked", this.handleSeek);
delete this.video.vsc;
}
if (this.srcObserver) this.srcObserver.disconnect();
let idx = tc.mediaElements.indexOf(this.video);
if (idx != -1) tc.mediaElements.splice(idx, 1);
};
tc.videoController.prototype.startSubtitleNudge = function () {
const isYouTube =
(this.video &&
this.video.currentSrc &&
this.video.currentSrc.includes("googlevideo.com")) ||
location.hostname.includes("youtube.com");
if (!isYouTube) return;
if (
!tc.settings.enableSubtitleNudge ||
this.nudgeIntervalId !== null ||
!this.video
!isSubtitleNudgeSupported(this.video) ||
!isSubtitleNudgeEnabledForVideo(this.video) ||
this.nudgeAnimationId !== null ||
!this.video ||
this.video.paused ||
this.video.playbackRate === 1.0
) {
return;
}
if (this.video.paused || this.video.playbackRate === 1.0) {
this.stopSubtitleNudge();
return;
}
log(`Nudge: Starting interval: ${tc.settings.subtitleNudgeInterval}ms.`, 5);
this.nudgeIntervalId = setInterval(() => {
if (
!this.video ||
this.video.paused ||
this.video.playbackRate === 1.0 ||
tc.isNudging
) {
// Store the target speed so we can always revert to it
this.targetSpeed = this.video.playbackRate;
const performNudge = () => {
// Check if we should stop
if (!this.video || this.video.paused || this.video.playbackRate === 1.0) {
this.stopSubtitleNudge();
return;
}
const currentRate = this.video.playbackRate;
const nudgeAmount = tc.settings.subtitleNudgeAmount;
// CRITICAL: Don't nudge if tab is hidden - prevents speed drift
if (document.hidden) {
if (!this.visibilityResumeHandler && this.video && this.video.ownerDocument) {
this.visibilityResumeHandler = () => {
if (this.video.ownerDocument.hidden) return;
this.video.ownerDocument.removeEventListener(
"visibilitychange",
this.visibilityResumeHandler,
true
);
this.visibilityResumeHandler = null;
this.startSubtitleNudge();
};
this.video.ownerDocument.addEventListener(
"visibilitychange",
this.visibilityResumeHandler,
true
);
}
this.nudgeAnimationId = null;
return;
}
// Set flag to prevent ratechange listener from interfering
tc.isNudging = true;
this.video.playbackRate = currentRate + nudgeAmount;
requestAnimationFrame(() => {
if (
this.video &&
Math.abs(this.video.playbackRate - (currentRate + nudgeAmount)) <
nudgeAmount * 1.5
) {
this.video.playbackRate = currentRate;
suppressNextNudgeRateChanges(this, 2);
// Cache values to avoid repeated property access
const targetSpeed = this.targetSpeed;
const nudgeAmount = tc.settings.subtitleNudgeAmount;
// Apply nudge from the stored target speed (not current rate)
this.video.playbackRate = targetSpeed + nudgeAmount;
// Revert synchronously after a microtask to ensure it happens immediately
Promise.resolve().then(() => {
if (this.video && targetSpeed) {
this.video.playbackRate = targetSpeed;
}
tc.isNudging = false;
});
}, tc.settings.subtitleNudgeInterval);
// Schedule next nudge
this.nudgeAnimationId = setTimeout(performNudge, tc.settings.subtitleNudgeInterval);
};
// Start the first nudge
this.nudgeAnimationId = setTimeout(performNudge, tc.settings.subtitleNudgeInterval);
log(`Nudge: Starting with interval ${tc.settings.subtitleNudgeInterval}ms.`, 5);
};
tc.videoController.prototype.stopSubtitleNudge = function () {
if (this.nudgeIntervalId !== null) {
if (this.nudgeAnimationId !== null) {
clearTimeout(this.nudgeAnimationId);
this.nudgeAnimationId = null;
log(`Nudge: Stopping.`, 5);
clearInterval(this.nudgeIntervalId);
this.nudgeIntervalId = null;
}
if (this.visibilityResumeHandler && this.video && this.video.ownerDocument) {
this.video.ownerDocument.removeEventListener(
"visibilitychange",
this.visibilityResumeHandler,
true
);
this.visibilityResumeHandler = null;
}
// Clear the animation state, but PRESERVE targetSpeed so getDesiredSpeed
// doesn't lose the user's intended speed if the site hijacks it.
};
tc.videoController.prototype.performImmediateNudge = function () {
if (
!isSubtitleNudgeSupported(this.video) ||
!isSubtitleNudgeEnabledForVideo(this.video) ||
!this.video ||
this.video.paused ||
this.video.playbackRate === 1.0 ||
document.hidden
) {
return;
}
const targetRate = this.targetSpeed || this.video.playbackRate;
const nudgeAmount = tc.settings.subtitleNudgeAmount;
tc.isNudging = true;
suppressNextNudgeRateChanges(this, 2);
this.video.playbackRate = targetRate + nudgeAmount;
// Revert synchronously via microtask
Promise.resolve().then(() => {
if (this.video) {
this.video.playbackRate = targetRate;
}
tc.isNudging = false;
});
log(`Immediate nudge performed at rate ${targetRate.toFixed(2)}`, 5);
};
tc.videoController.prototype.setupYouTubeAutoHide = function (wrapper) {
if (!wrapper || !isOnYouTube()) return;
const video = this.video;
const ytPlayer = video.closest(".html5-video-player");
if (!ytPlayer) {
log("YouTube player not found for auto-hide setup", 4);
return;
}
const syncControllerVisibility = () => {
// YouTube adds ytp-autohide class to the player when controls should be hidden
// We mirror this class state to enable CSS-based hiding
// The vsc-hidden class (from V key) takes precedence via CSS specificity
if (ytPlayer.classList.contains("ytp-autohide")) {
wrapper.classList.add("ytp-autohide");
// Immediately end any temporary "vsc-show" state to hide with YouTube
// UNLESS it was forced by a shortcut (vsc-forced-show)
if (!wrapper.classList.contains("vsc-forced-show")) {
wrapper.classList.remove("vsc-show");
if (wrapper.showTimeOut) {
clearTimeout(wrapper.showTimeOut);
wrapper.showTimeOut = undefined;
}
}
log("YouTube controls hidden, hiding controller", 5);
} else {
wrapper.classList.remove("ytp-autohide");
log("YouTube controls visible, showing controller", 5);
}
};
// Initial sync
syncControllerVisibility();
// Observe YouTube player class changes
this.youTubeAutoHideObserver = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === "attributes" && mutation.attributeName === "class") {
syncControllerVisibility();
}
});
});
this.youTubeAutoHideObserver.observe(ytPlayer, {
attributes: true,
attributeFilter: ["class"]
});
log("YouTube auto-hide observer setup complete", 4);
// Also reveal on hover/activity independently of YouTube's own controls
// for immediate responsiveness, UNLESS Speeder is actually toggled hidden (vsc-hidden)
const resetTimer = () => {
showController(wrapper, tc.settings.hideWithControlsTimer * 1000);
};
const activityEvents = ["mousemove", "mousedown", "touchstart"];
activityEvents.forEach((type) => {
video.addEventListener(type, resetTimer, { passive: true });
wrapper.addEventListener(type, resetTimer, { passive: true });
ytPlayer.addEventListener(type, resetTimer, { passive: true });
});
// Store a cleanup function
this.youTubeAutoHideCleanup = () => {
activityEvents.forEach((type) => {
video.removeEventListener(type, resetTimer);
wrapper.removeEventListener(type, resetTimer);
ytPlayer.removeEventListener(type, resetTimer);
});
};
};
tc.videoController.prototype.setupGenericAutoHide = function (wrapper) {
if (!wrapper) return;
const video = this.video;
let timer = null;
const resetTimer = () => {
wrapper.classList.remove("vsc-idle-hidden");
showController(wrapper, tc.settings.hideWithControlsTimer * 1000);
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
// Only hide if the video is not paused
// (Many players keep controls visible while paused)
// However, the user said "Reveal on every mouse and keyboard input"
// and "auto-hidden after timespan".
// We'll follow the timer strictly.
wrapper.classList.add("vsc-idle-hidden");
log("Generic hide: controller hidden due to inactivity", 5);
}, tc.settings.hideWithControlsTimer * 1000);
};
// Initial show/timer
resetTimer();
// The wrapper covers the player area on most sites due to inject.css styles,
// but we listen on both the video and the wrapper for maximum coverage.
const activityEvents = ["mousemove", "mousedown", "keydown", "touchstart"];
const parentEl = video.parentElement;
activityEvents.forEach((type) => {
video.addEventListener(type, resetTimer, { passive: true });
wrapper.addEventListener(type, resetTimer, { passive: true });
if (parentEl) {
parentEl.addEventListener(type, resetTimer, { passive: true });
}
});
// Also reset timer on play/pause events to ensure sync when player state changes
video.addEventListener("play", resetTimer, { passive: true });
video.addEventListener("pause", resetTimer, { passive: true });
// Store a cleanup function
this.genericAutoHideCleanup = () => {
if (timer) clearTimeout(timer);
activityEvents.forEach((type) => {
video.removeEventListener(type, resetTimer);
wrapper.removeEventListener(type, resetTimer);
if (parentEl) {
parentEl.removeEventListener(type, resetTimer);
}
});
video.removeEventListener("play", resetTimer);
video.removeEventListener("pause", resetTimer);
};
log(`Generic auto-hide setup complete with ${tc.settings.hideWithControlsTimer}s timer`, 4);
};
tc.videoController.prototype.initializeControls = function () {
const doc = this.video.ownerDocument;
const speed = this.video.playbackRate.toFixed(2);
// Fix for videos rendered after page load - use relative positioning
var top = "10px",
left = "10px";
// Try to get actual position, but fallback to default if not available
if (this.video.offsetTop > 0 || this.video.offsetLeft > 0) {
top = Math.max(this.video.offsetTop, 0) + "px";
left = Math.max(this.video.offsetLeft, 0) + "px";
}
var wrapper = doc.createElement("div");
wrapper.classList.add("vsc-controller");
if (!this.video.src && !this.video.currentSrc)
wrapper.classList.add("vsc-nosource");
if (tc.settings.startHidden) wrapper.classList.add("vsc-hidden");
// Use lower z-index for non-YouTube sites to avoid overlapping modals
if (!isOnYouTube()) wrapper.classList.add("vsc-non-youtube");
var shadow = wrapper.attachShadow({ mode: "open" });
shadow.innerHTML = `<style> @import "${chrome.runtime.getURL("shadow.css")}"; </style><div id="controller" style="top:${top}; left:${left}; opacity:${tc.settings.controllerOpacity}"><span data-action="drag" class="draggable">${speed}</span><span id="controls"><button data-action="rewind" class="rw">«</button><button data-action="slower"></button><button data-action="faster">+</button><button data-action="advance" class="rw">»</button><button data-action="display" class="hideButton">×</button></span></div>`;
this.speedIndicator = shadow.querySelector(".draggable");
shadow.querySelector(".draggable").addEventListener(
var shadowStylesheet = doc.createElement("link");
shadowStylesheet.rel = "stylesheet";
shadowStylesheet.href = chrome.runtime.getURL("shadow.css");
shadow.appendChild(shadowStylesheet);
var controller = doc.createElement("div");
controller.id = "controller";
controller.style.opacity = String(tc.settings.controllerOpacity);
this.controllerLocation = applyControllerLocationToElement(
controller,
this.controllerLocation
);
var dragHandle = doc.createElement("span");
dragHandle.dataset.action = "drag";
dragHandle.className = "draggable";
dragHandle.textContent = speed;
var controls = doc.createElement("span");
controls.id = "controls";
var buttonConfig = Array.isArray(tc.settings.controllerButtons)
? tc.settings.controllerButtons
: ["rewind", "slower", "faster", "advance", "display"];
var subtitleNudgeIndicator = null;
buttonConfig.forEach(function (btnId) {
if (btnId === "nudge") {
subtitleNudgeIndicator = doc.createElement("span");
subtitleNudgeIndicator.id = "nudge-indicator";
subtitleNudgeIndicator.setAttribute("role", "button");
subtitleNudgeIndicator.setAttribute("aria-live", "polite");
subtitleNudgeIndicator.setAttribute("tabindex", "0");
controls.appendChild(subtitleNudgeIndicator);
} else {
var def = controllerButtonDefs[btnId];
if (def) {
controls.appendChild(
createControllerButton(doc, btnId, def.label, def.className)
);
}
}
});
var nudgeFlashIndicator = doc.createElement("span");
nudgeFlashIndicator.id = "nudge-flash-indicator";
nudgeFlashIndicator.setAttribute("aria-hidden", "true");
controller.appendChild(dragHandle);
controller.appendChild(nudgeFlashIndicator);
controller.appendChild(controls);
shadow.appendChild(controller);
this.speedIndicator = dragHandle;
this.subtitleNudgeIndicator = subtitleNudgeIndicator;
this.nudgeFlashIndicator = nudgeFlashIndicator;
if (subtitleNudgeIndicator) {
updateSubtitleNudgeIndicator(this.video);
}
dragHandle.addEventListener(
"mousedown",
(e) => {
runAction(
@@ -426,41 +1629,93 @@ function defineVideoController() {
true
);
});
shadow
.querySelector("#controller")
.addEventListener("click", (e) => e.stopPropagation(), false);
shadow
.querySelector("#controller")
.addEventListener("mousedown", (e) => e.stopPropagation(), false);
if (subtitleNudgeIndicator) {
subtitleNudgeIndicator.addEventListener(
"click",
(e) => {
var video = this.video;
if (video) {
var newState = !isSubtitleNudgeEnabledForVideo(video);
setSubtitleNudgeEnabledForVideo(video, newState);
}
e.stopPropagation();
},
true
);
}
controller.addEventListener("click", (e) => e.stopPropagation(), false);
controller.addEventListener("mousedown", (e) => e.stopPropagation(), false);
// Setup auto-hide observers if enabled
if (tc.settings.hideWithControls) {
if (isOnYouTube()) {
this.setupYouTubeAutoHide(wrapper);
} else {
this.setupGenericAutoHide(wrapper);
}
}
var fragment = doc.createDocumentFragment();
fragment.appendChild(wrapper);
const parentEl = this.parent || this.video.parentElement;
log(`Inserting controller: parentEl=${!!parentEl}, parentNode=${!!parentEl?.parentNode}, hostname=${location.hostname}`, 4);
if (!parentEl || !parentEl.parentNode) {
log("No suitable parent found, appending to body", 4);
doc.body.appendChild(fragment);
return wrapper;
}
switch (true) {
case location.hostname == "www.amazon.com":
case location.hostname == "www.reddit.com":
case /hbogo\./.test(location.hostname):
parentEl.parentElement.insertBefore(fragment, parentEl);
break;
case location.hostname == "www.facebook.com":
let p =
parentEl.parentElement.parentElement.parentElement.parentElement
.parentElement.parentElement.parentElement;
if (p && p.firstChild) p.insertBefore(fragment, p.firstChild);
else parentEl.insertBefore(fragment, parentEl.firstChild);
break;
case location.hostname == "tv.apple.com":
const r = parentEl.getRootNode();
const s = r && r.querySelector ? r.querySelector(".scrim") : null;
if (s) s.prepend(fragment);
else parentEl.insertBefore(fragment, parentEl.firstChild);
break;
default:
parentEl.insertBefore(fragment, parentEl.firstChild);
try {
switch (true) {
case location.hostname == "www.amazon.com":
case location.hostname == "www.reddit.com":
case /hbogo\./.test(location.hostname):
log("Using parentElement.parentElement insertion", 5);
parentEl.parentElement.insertBefore(fragment, parentEl);
break;
case location.hostname == "www.facebook.com":
log("Using Facebook-specific insertion", 5);
let p =
parentEl.parentElement.parentElement.parentElement.parentElement
.parentElement.parentElement.parentElement;
if (p && p.firstChild) p.insertBefore(fragment, p.firstChild);
else parentEl.insertBefore(fragment, parentEl.firstChild);
break;
case location.hostname == "tv.apple.com":
log("Using Apple TV-specific insertion", 5);
const r = parentEl.getRootNode();
const s = r && r.querySelector ? r.querySelector(".scrim") : null;
if (s) s.prepend(fragment);
else parentEl.insertBefore(fragment, parentEl.firstChild);
break;
case location.hostname == "www.youtube.com":
case location.hostname == "m.youtube.com":
case location.hostname == "music.youtube.com":
// YouTube's player DOM has .html5-video-container (video's parent) as a
// low layer with overlay siblings (.ytp-player-content, etc.) on top that
// intercept mouse events. Insert into .html5-video-player (the player
// root) so the controller sits above all overlay layers.
log("Using YouTube-specific insertion", 5);
var ytPlayer = parentEl.closest(".html5-video-player");
if (ytPlayer) {
ytPlayer.insertBefore(fragment, ytPlayer.firstChild);
} else {
parentEl.insertBefore(fragment, parentEl.firstChild);
}
break;
default:
log("Using default insertion method", 5);
parentEl.insertBefore(fragment, parentEl.firstChild);
}
log("Controller successfully inserted into DOM", 4);
} catch (error) {
log(`Error inserting controller: ${error.message}`, 2);
// Fallback to body insertion
doc.body.appendChild(fragment);
}
return wrapper;
};
}
@@ -469,92 +1724,229 @@ function escapeStringRegExp(str) {
const m = /[|\\{}()[\]^$+*?.]/g;
return str.replace(m, "\\$&");
}
function isBlacklisted() {
let b = false;
const l = tc.settings.blacklist ? tc.settings.blacklist.split("\n") : [];
l.forEach((m) => {
if (b) return;
m = m.replace(regStrip, "");
if (m.length == 0) return;
let r;
if (m.startsWith("/") && m.lastIndexOf("/") > 0) {
function applySiteRuleOverrides() {
if (!Array.isArray(tc.settings.siteRules) || tc.settings.siteRules.length === 0) {
return false;
}
var currentUrl = location.href;
var matchedRule = null;
for (var i = 0; i < tc.settings.siteRules.length; i++) {
var rule = tc.settings.siteRules[i];
var pattern = rule.pattern;
if (!pattern || pattern.length === 0) continue;
var regex;
if (pattern.startsWith("/") && pattern.lastIndexOf("/") > 0) {
try {
const ls = m.lastIndexOf("/");
r = new RegExp(m.substring(1, ls), m.substring(ls + 1));
var lastSlash = pattern.lastIndexOf("/");
regex = new RegExp(
pattern.substring(1, lastSlash),
pattern.substring(lastSlash + 1)
);
} catch (e) {
log(`Invalid regex: ${m}. ${e.message}`, 2);
return;
log(`Invalid site rule regex: ${pattern}. ${e.message}`, 2);
continue;
}
} else r = new RegExp(escapeStringRegExp(m));
if (r && r.test(location.href)) b = true;
} else {
regex = new RegExp(escapeStringRegExp(pattern));
}
if (regex && regex.test(currentUrl)) {
matchedRule = rule;
break;
}
}
if (!matchedRule) return false;
tc.activeSiteRule = matchedRule;
log(`Matched site rule: ${matchedRule.pattern}`, 4);
// Check if extension should be enabled/disabled on this site
if (matchedRule.enabled === false) {
log(`Extension disabled for site: ${currentUrl}`, 4);
return true;
} else if (matchedRule.disableExtension === true) {
// Handle old format
log(`Extension disabled (legacy) for site: ${currentUrl}`, 4);
return true;
}
// Override general settings with site-specific overrides
const siteSettings = [
"startHidden",
"hideWithControls",
"hideWithControlsTimer",
"controllerLocation",
"rememberSpeed",
"forceLastSavedSpeed",
"audioBoolean",
"controllerOpacity",
"enableSubtitleNudge",
"subtitleNudgeInterval"
];
siteSettings.forEach((key) => {
if (matchedRule[key] !== undefined) {
log(`Overriding ${key} for site: ${matchedRule[key]}`, 4);
tc.settings[key] = matchedRule[key];
}
});
if (b) log(`Page ${location.href} blacklisted.`, 4);
return b;
}
var coolDown = false;
function refreshCoolDown() {
if (coolDown) clearTimeout(coolDown);
coolDown = setTimeout(function () {
coolDown = false;
}, 1000);
if (Array.isArray(matchedRule.controllerButtons)) {
log(`Overriding controllerButtons for site`, 4);
tc.settings.controllerButtons = matchedRule.controllerButtons;
}
// Override key bindings with site-specific shortcuts
if (Array.isArray(matchedRule.shortcuts) && matchedRule.shortcuts.length > 0) {
var overriddenActions = new Set();
matchedRule.shortcuts.forEach((shortcut) => {
overriddenActions.add(shortcut.action);
});
// Keep global bindings that aren't overridden, add site-specific ones
tc.settings.keyBindings = tc.settings.keyBindings
.filter((binding) => !overriddenActions.has(binding.action))
.concat(
matchedRule.shortcuts.map((shortcut) =>
normalizeStoredBinding(shortcut)
).filter(Boolean)
);
}
return false;
}
function setupListener() {
if (document.vscRateListenerAttached) return;
function updateSpeedFromEvent(video, fromUserInput = false) {
function shouldPreserveDesiredSpeed(video, speed) {
if (!video || !video.vsc) return false;
var desiredSpeed = getDesiredSpeed(video);
if (!isValidSpeed(desiredSpeed) || Math.abs(speed - desiredSpeed) <= 0.01) {
return false;
}
return (
video.paused === true ||
(typeof video.vsc.speedRestoreUntil === "number" &&
video.vsc.speedRestoreUntil > Date.now())
);
}
function setupListener(root) {
root = root || document;
if (root.vscRateListenerAttached) return;
function updateSpeedFromEvent(video) {
if (!video.vsc || !video.vsc.speedIndicator) return;
var speed = Number(video.playbackRate.toFixed(2));
var speed = video.playbackRate; // Preserve full precision (e.g. 0.0625)
video.vsc.speedIndicator.textContent = speed.toFixed(2);
tc.settings.speeds[video.currentSrc || "unknown_src"] = speed;
tc.settings.lastSpeed = speed;
chrome.storage.sync.set({ lastSpeed: speed }, () => {});
if (fromUserInput) {
runAction("blink", 1000, null, video);
video.vsc.targetSpeed = speed;
var sourceKey = getVideoSourceKey(video);
if (sourceKey !== "unknown_src") {
tc.settings.speeds[sourceKey] = speed;
}
tc.settings.lastSpeed = speed;
schedulePersistLastSpeed(speed);
if (video.vsc) {
if (speed === 1.0 || video.paused) video.vsc.stopSubtitleNudge();
else video.vsc.startSubtitleNudge();
}
}
document.addEventListener(
root.addEventListener(
"ratechange",
function (event) {
if (tc.isNudging) return;
if (coolDown) {
event.stopImmediatePropagation();
return;
}
var video = event.target;
if (!video || typeof video.playbackRate === "undefined" || !video.vsc)
return;
if (shouldIgnoreSuppressedRateChange(video)) return;
if (tc.settings.forceLastSavedSpeed) {
if (event.detail && event.detail.origin === "videoSpeed") {
video.playbackRate = event.detail.speed;
updateSpeedFromEvent(video, event.detail.fromUserInput === true);
updateSpeedFromEvent(video);
} else {
video.playbackRate = tc.settings.lastSpeed;
video.playbackRate = sanitizeSpeed(tc.settings.lastSpeed, 1.0);
}
event.stopImmediatePropagation();
} else {
updateSpeedFromEvent(video, video.vscIsDirectlySettingRate === true);
if (video.vscIsDirectlySettingRate)
delete video.vscIsDirectlySettingRate;
var currentSpeed = video.playbackRate; // Preserve full precision (e.g. 0.0625)
var desiredSpeed = getDesiredSpeed(video);
var pendingRateChange = takePendingRateChange(video, currentSpeed);
if (pendingRateChange) {
updateSpeedFromEvent(video);
return;
}
if (shouldPreserveDesiredSpeed(video, currentSpeed)) {
log(
`Ignoring external rate change to ${currentSpeed.toFixed(4)} while preserving ${desiredSpeed.toFixed(4)}`,
4
);
video.vsc.speedIndicator.textContent = desiredSpeed.toFixed(2);
scheduleSpeedRestore(video, desiredSpeed, "pause/play or seek");
return;
}
updateSpeedFromEvent(video);
}
},
true
);
document.vscRateListenerAttached = true;
root.vscRateListenerAttached = true;
}
var vscInitializedDocuments = new Set();
function initializeWhenReady(doc) {
if (vscInitializedDocuments.has(doc) || !doc.body) return;
if (doc.readyState === "complete") {
initializeNow(doc);
function clearPendingInitialization(doc) {
if (!doc || !doc.vscPendingInitializeHandler) return;
var handler = doc.vscPendingInitializeHandler;
doc.removeEventListener("DOMContentLoaded", handler);
doc.removeEventListener("readystatechange", handler);
if (doc.defaultView) {
doc.defaultView.removeEventListener("load", handler);
}
delete doc.vscPendingInitializeHandler;
doc.vscPendingForceReinit = false;
}
function tryInitializeDocument(doc, forceReinit) {
if (!doc) return false;
if ((!forceReinit && vscInitializedDocuments.has(doc)) || !doc.body) {
return false;
}
initializeNow(doc, forceReinit);
clearPendingInitialization(doc);
return true;
}
function initializeWhenReady(doc, forceReinit = false) {
if (!doc) return;
doc.vscPendingForceReinit = doc.vscPendingForceReinit === true || forceReinit;
if (tryInitializeDocument(doc, doc.vscPendingForceReinit)) {
return;
}
if (doc.vscPendingInitializeHandler) return;
var pendingInitializeHandler = function () {
tryInitializeDocument(doc, doc.vscPendingForceReinit === true);
};
doc.vscPendingInitializeHandler = pendingInitializeHandler;
doc.addEventListener("DOMContentLoaded", pendingInitializeHandler);
doc.addEventListener("readystatechange", pendingInitializeHandler);
if (doc.defaultView) {
doc.defaultView.addEventListener("load", pendingInitializeHandler);
doc.defaultView.setTimeout(pendingInitializeHandler, 0);
} else {
doc.addEventListener("DOMContentLoaded", () => initializeNow(doc), {
once: true
});
setTimeout(pendingInitializeHandler, 0);
}
}
function inIframe() {
@@ -564,41 +1956,18 @@ function inIframe() {
return true;
}
}
function getShadow(parent) {
let r = [];
function gC(p) {
if (p.firstElementChild) {
var c = p.firstElementChild;
do {
r.push(c);
gC(c);
if (c.shadowRoot) r.push(...getShadow(c.shadowRoot));
c = c.nextElementSibling;
} while (c);
}
}
gC(parent);
return r;
}
function initializeNow(doc) {
if (vscInitializedDocuments.has(doc) || !doc.body) return;
if (!tc.settings.enabled) return;
if (!doc.body.classList.contains("vsc-initialized"))
doc.body.classList.add("vsc-initialized");
if (typeof tc.videoController === "undefined") defineVideoController();
setupListener();
var docs = Array(doc);
function attachKeydownListeners(doc) {
var docs = [doc];
try {
if (inIframe()) docs.push(window.top.document);
} catch (e) {}
docs.forEach(function (d) {
if (d.vscKeydownListenerAttached) return; // Prevent duplicate listeners
d.addEventListener(
if (inIframe() && window.top.document !== doc) docs.push(window.top.document);
} catch (e) { }
docs.forEach(function (keyDoc) {
if (keyDoc.vscKeydownListenerAttached) return;
keyDoc.addEventListener(
"keydown",
function (event) {
var keyCode = event.keyCode;
if (
!event.getModifierState ||
event.getModifierState("Alt") ||
@@ -607,133 +1976,207 @@ function initializeNow(doc) {
event.getModifierState("Meta") ||
event.getModifierState("Hyper") ||
event.getModifierState("OS")
)
) {
return;
}
if (
event.target.nodeName === "INPUT" ||
event.target.nodeName === "TEXTAREA" ||
event.target.isContentEditable
)
) {
return;
}
if (!tc.mediaElements.length) return;
var item = tc.settings.keyBindings.find((item) => item.key === keyCode);
var item = tc.settings.keyBindings.find(function (binding) {
return matchesKeyBinding(binding, event);
});
if (item) {
runAction(item.action, item.value, event);
if (item.force === "true") {
event.preventDefault();
event.stopPropagation();
}
// Always prevent default and stop propagation for Speeder shortcuts
// to prevent the website (e.g. YouTube) from reacting to these keys.
event.preventDefault();
event.stopPropagation();
}
return false;
},
true
);
d.vscKeydownListenerAttached = true;
keyDoc.vscKeydownListenerAttached = true;
});
}
function attachMutationObserver(root) {
if (root.vscMutationObserverAttached) return;
var pendingMutations = [];
var mutationProcessingScheduled = false;
var observer = new MutationObserver(function (mutations) {
pendingMutations.push(...mutations);
if (mutationProcessingScheduled) return;
mutationProcessingScheduled = true;
requestIdle(
function () {
var mutationsToProcess = pendingMutations.splice(0);
mutationProcessingScheduled = false;
mutationsToProcess.forEach(function (mutation) {
if (mutation.type === "childList") {
mutation.addedNodes.forEach(function (node) {
// Skip text nodes, comments, etc. — only elements can contain media
if (node.nodeType !== Node.ELEMENT_NODE) return;
scanNodeForMedia(node, node.parentNode || mutation.target, true);
});
mutation.removedNodes.forEach(function (node) {
if (node.nodeType !== Node.ELEMENT_NODE) return;
scanNodeForMedia(node, node.parentNode || mutation.target, false);
});
return;
}
if (mutation.type !== "attributes") return;
var target = mutation.target;
if (
isMediaElement(target) &&
(mutation.attributeName === "src" ||
mutation.attributeName === "currentSrc")
) {
ensureController(target, target.parentElement || target.parentNode);
return;
}
if (
mutation.attributeName === "aria-hidden" &&
target.attributes["aria-hidden"] &&
target.attributes["aria-hidden"].value === "false"
) {
scanNodeForMedia(
target,
target.parentNode || root.host || mutation.target,
true
);
}
});
},
{ timeout: 1000 }
);
});
if (!doc.vscMutationObserverAttached) {
const observer = new MutationObserver(function (mutations) {
requestIdleCallback(
(_) => {
mutations.forEach(function (mutation) {
switch (mutation.type) {
case "childList":
mutation.addedNodes.forEach(function (node) {
if (typeof node === "function") return;
checkForVideo(node, node.parentNode || mutation.target, true);
});
mutation.removedNodes.forEach(function (node) {
if (typeof node === "function") return;
checkForVideo(
node,
node.parentNode || mutation.target,
false
);
});
break;
case "attributes":
if (
mutation.target.attributes["aria-hidden"] &&
mutation.target.attributes["aria-hidden"].value == "false"
) {
var flattenedNodes = getShadow(document.body);
var node = flattenedNodes.filter(
(x) => x.tagName == "VIDEO"
)[0];
if (node) {
if (node.vsc) node.vsc.remove();
checkForVideo(
node,
node.parentNode || mutation.target,
true
);
}
}
break;
}
});
},
{ timeout: 1000 }
);
});
function checkForVideo(node, parent, added) {
if (!added && document.body.contains(node)) return;
if (
node.nodeName === "VIDEO" ||
(node.nodeName === "AUDIO" && tc.settings.audioBoolean)
) {
if (added) {
if (!node.vsc) node.vsc = new tc.videoController(node, parent);
} else {
if (node.vsc) node.vsc.remove();
}
} else if (node.children != undefined) {
for (var i = 0; i < node.children.length; i++) {
const child = node.children[i];
checkForVideo(child, child.parentNode || parent, added);
}
}
observer.observe(root, {
attributeFilter: ["aria-hidden", "src", "currentSrc"],
childList: true,
subtree: true,
attributes: true
});
root.vscMutationObserverAttached = true;
}
function attachMediaDetectionListeners(root) {
if (root.vscMediaEventListenersAttached) return;
var handleDetectedMedia = function (event) {
var target = event.target;
if (!isMediaElement(target)) return;
ensureController(target, target.parentElement || target.parentNode);
};
[
"loadstart",
"loadeddata",
"loadedmetadata",
"canplay",
"playing",
"play"
].forEach(function (eventName) {
root.addEventListener(eventName, handleDetectedMedia, true);
});
root.vscMediaEventListenersAttached = true;
}
function attachIframeListeners(doc) {
Array.from(doc.getElementsByTagName("iframe")).forEach(function (frame) {
if (!frame.vscLoadListenerAttached) {
frame.addEventListener("load", function () {
try {
if (frame.contentDocument) {
initializeWhenReady(frame.contentDocument, true);
}
} catch (e) { }
});
frame.vscLoadListenerAttached = true;
}
observer.observe(doc, {
attributeFilter: ["aria-hidden"],
childList: true,
subtree: true
});
doc.vscMutationObserverAttached = true;
try {
if (frame.contentDocument) {
initializeWhenReady(frame.contentDocument);
}
} catch (e) { }
});
}
function attachNavigationListeners() {
if (window.vscNavigationListenersAttached) return;
var scheduleRescan = function () {
clearTimeout(window.vscNavigationRescanTimer);
window.vscNavigationRescanTimer = setTimeout(function () {
initializeWhenReady(document, true);
}, 300);
};
["pushState", "replaceState"].forEach(function (method) {
if (typeof history[method] !== "function") return;
var original = history[method];
history[method] = function () {
var result = original.apply(this, arguments);
scheduleRescan();
return result;
};
});
window.addEventListener("popstate", scheduleRescan);
window.addEventListener("hashchange", scheduleRescan);
window.vscNavigationListenersAttached = true;
}
function initializeNow(doc, forceReinit = false) {
if ((!forceReinit && vscInitializedDocuments.has(doc)) || !doc.body) return;
var siteDisabled = applySiteRuleOverrides();
if (!tc.settings.enabled || siteDisabled) return;
if (!doc.body.classList.contains("vsc-initialized")) {
doc.body.classList.add("vsc-initialized");
}
if (typeof tc.videoController === "undefined") defineVideoController();
attachKeydownListeners(doc);
attachNavigationListeners();
observeRoot(doc);
if (forceReinit) {
log("Force re-initialization requested", 4);
}
const q = tc.settings.audioBoolean ? "video,audio" : "video";
const foundVideos = doc.querySelectorAll(q);
foundVideos.forEach((v) => {
if (!v.vsc) new tc.videoController(v, v.parentElement);
});
Array.from(doc.getElementsByTagName("iframe")).forEach((f) => {
if (f.vscLoadListenerAttached) return;
f.addEventListener("load", () => {
try {
if (f.contentDocument) {
initializeWhenReady(f.contentDocument);
}
} catch (e) {
// Silently ignore CORS errors
}
});
f.vscLoadListenerAttached = true;
try {
if (f.contentDocument) {
initializeWhenReady(f.contentDocument);
}
} catch (e) {
// Silently ignore CORS errors
}
});
vscInitializedDocuments.add(doc);
}
function setSpeed(video, speed, isInitialCall = false, isUserKeyPress = false) {
const numericSpeed = Number(speed);
if (isNaN(numericSpeed) || numericSpeed <= 0 || numericSpeed > 16) return;
if (!isValidSpeed(numericSpeed)) {
log(
`Invalid speed rejected: ${speed}, must be between ${MIN_SPEED} and ${MAX_SPEED}`,
2
);
return;
}
if (!video || !video.vsc || !video.vsc.speedIndicator) return;
log(
@@ -743,10 +2186,16 @@ function setSpeed(video, speed, isInitialCall = false, isUserKeyPress = false) {
tc.settings.lastSpeed = numericSpeed;
video.vsc.speedIndicator.textContent = numericSpeed.toFixed(2);
// Update the target speed for nudge so it knows what to revert to
video.vsc.targetSpeed = numericSpeed;
if (isUserKeyPress && !isInitialCall && video.vsc && video.vsc.div) {
runAction("blink", 1000, null, video); // Pass video to blink
extendSpeedRestoreWindow(video); // Protect against immediate site-driven resets
}
// Try YouTube's native speed API first — keeps subtitles in sync without nudge
var usedNativeSpeed = false;
if (tc.settings.forceLastSavedSpeed) {
video.dispatchEvent(
new CustomEvent("ratechange", {
@@ -759,16 +2208,22 @@ function setSpeed(video, speed, isInitialCall = false, isUserKeyPress = false) {
);
} else {
if (Math.abs(video.playbackRate - numericSpeed) > 0.001) {
if (isUserKeyPress && !isInitialCall) {
video.vscIsDirectlySettingRate = true; // Set flag for ratechange listener
rememberPendingRateChange(video, numericSpeed);
usedNativeSpeed = tryYouTubeNativeSpeed(video, numericSpeed);
if (!usedNativeSpeed) {
video.playbackRate = numericSpeed;
}
video.playbackRate = numericSpeed;
}
}
if (!isInitialCall) refreshCoolDown();
if (video.vsc) {
if (numericSpeed === 1.0 || video.paused) video.vsc.stopSubtitleNudge();
else video.vsc.startSubtitleNudge();
if (numericSpeed === 1.0 || video.paused) {
video.vsc.stopSubtitleNudge();
} else if (usedNativeSpeed) {
// YouTube's native API handles subtitle sync — no nudge needed
video.vsc.stopSubtitleNudge();
} else {
video.vsc.startSubtitleNudge();
}
}
}
@@ -776,6 +2231,7 @@ function runAction(action, value, e) {
log("runAction Begin", 5);
var mediaTagsToProcess;
const specificVideo = arguments[3] || null;
var subtitleNudgeToggleValue = null;
if (specificVideo) {
mediaTagsToProcess = [specificVideo];
@@ -796,8 +2252,18 @@ function runAction(action, value, e) {
} else {
mediaTagsToProcess = tc.mediaElements;
}
if (action === "settings") {
chrome.runtime.sendMessage({ action: "openOptions" });
return;
}
if (mediaTagsToProcess.length === 0 && action !== "display") return;
if (action === "toggleSubtitleNudge" && mediaTagsToProcess.length > 0) {
subtitleNudgeToggleValue = !isSubtitleNudgeEnabledForVideo(
mediaTagsToProcess[0]
);
}
mediaTagsToProcess.forEach(function (v) {
if (!v.vsc) return; // Don't process videos without a controller
var controller = v.vsc.div;
@@ -808,73 +2274,112 @@ function runAction(action, value, e) {
"slower",
"reset",
"fast",
"move",
"pause",
"muted",
"mark",
"jump",
"drag"
"drag",
"toggleSubtitleNudge",
"display"
];
if (userDrivenActionsThatShowController.includes(action)) {
showController(controller);
if (userDrivenActionsThatShowController.includes(action) && action !== "display") {
showController(controller, 2000, true);
}
if (v.classList.contains("vsc-cancelled")) return;
const numValue = parseFloat(value);
switch (action) {
case "rewind":
isUserSeek = true;
extendSpeedRestoreWindow(v);
v.currentTime -= numValue;
break;
case "advance":
isUserSeek = true;
extendSpeedRestoreWindow(v);
v.currentTime += numValue;
break;
case "faster":
setSpeed(
v,
Math.min(
(v.playbackRate < 0.07 ? 0.07 : v.playbackRate) + numValue,
16
),
false,
true
);
var fasterStep = numValue;
// Use grid-snapping: always move to the next multiple of fasterStep
// Add a tiny epsilon (1% of step) to jump clear of the current point
var newFasterSpeed = Math.ceil((v.playbackRate + (fasterStep * 0.01)) / fasterStep) * fasterStep;
// Clean up JS floating point math (e.g. 0.30000000000000004 -> 0.30)
newFasterSpeed = Math.round(newFasterSpeed * 1000) / 1000;
setSpeed(v, Math.min(newFasterSpeed, MAX_SPEED), false, true);
break;
case "slower":
setSpeed(v, Math.max(v.playbackRate - numValue, 0.07), false, true);
var slowerStep = numValue;
// Use grid-snapping: always move to the previous multiple of slowerStep
// Subtract a tiny epsilon (1% of step) to jump clear of the current point
var newSlowerSpeed = Math.floor((v.playbackRate - (slowerStep * 0.01)) / slowerStep) * slowerStep;
// Clean up JS floating point math
newSlowerSpeed = Math.round(newSlowerSpeed * 1000) / 1000;
setSpeed(v, Math.max(newSlowerSpeed, MIN_SPEED), false, true);
break;
case "reset":
resetSpeed(v, 1.0, false); // Use enhanced resetSpeed
break;
case "fast":
resetSpeed(v, numValue, true); // Use enhanced resetSpeed
var preferredSpeed = numValue;
// Apply site-specific preferred speed override if available
if (tc.activeSiteRule && typeof tc.activeSiteRule.preferredSpeed === "number") {
preferredSpeed = tc.activeSiteRule.preferredSpeed;
}
resetSpeed(v, preferredSpeed, true);
break;
case "display":
controller.classList.add("vsc-manual");
controller.classList.toggle("vsc-hidden");
if (controller.classList.contains("vsc-hidden")) {
controller.classList.remove("vsc-hidden");
showController(controller, 2000, true);
} else {
controller.classList.add("vsc-hidden");
// Clear any show state when explicitly hiding
controller.classList.remove("vsc-show");
controller.classList.remove("vsc-forced-show");
if (controller.showTimeOut) {
clearTimeout(controller.showTimeOut);
controller.showTimeOut = undefined;
}
}
break;
case "blink":
log(`Blink action: controller hidden=${controller.classList.contains("vsc-hidden")}, timeout=${controller.blinkTimeOut !== undefined}, duration=${numValue}`, 5);
if (
controller.classList.contains("vsc-hidden") ||
controller.blinkTimeOut !== undefined
) {
clearTimeout(controller.blinkTimeOut);
var restoreHidden =
controller.restoreHiddenAfterBlink === true ||
controller.classList.contains("vsc-hidden");
if (controller.blinkTimeOut !== undefined) {
clearTimeout(controller.blinkTimeOut);
}
controller.restoreHiddenAfterBlink = restoreHidden;
controller.classList.remove("vsc-hidden");
log(`Controller shown, setting timeout for ${numValue || 1000}ms`, 5);
controller.blinkTimeOut = setTimeout(() => {
if (
!(
controller.classList.contains("vsc-manual") &&
!controller.classList.contains("vsc-hidden")
)
) {
if (controller.restoreHiddenAfterBlink === true) {
controller.classList.add("vsc-hidden");
log("Controller auto-hidden after blink timeout", 5);
} else {
log("Controller kept visible", 5);
}
controller.restoreHiddenAfterBlink = false;
controller.blinkTimeOut = undefined;
}, numValue || 1000); // FIXED: Use numValue for consistency
}, numValue || 1000);
}
break;
case "drag":
if (e) handleDrag(v, e);
break;
case "move":
cycleControllerLocation(v);
break;
case "pause":
pause(v);
break;
@@ -887,6 +2392,9 @@ function runAction(action, value, e) {
case "jump":
jumpToMark(v);
break;
case "toggleSubtitleNudge":
setSubtitleNudgeEnabledForVideo(v, subtitleNudgeToggleValue);
break;
}
});
log("runAction End", 5);
@@ -898,7 +2406,7 @@ function pause(v) {
}
function resetSpeed(v, target, isFastKey = false) {
const videoId = v.currentSrc || v.src || "default";
const videoId = getVideoSourceKey(v);
const currentSpeed = v.playbackRate;
if (isFastKey) {
@@ -941,11 +2449,15 @@ function setMark(v) {
v.vsc.mark = v.currentTime;
}
function jumpToMark(v) {
if (v.vsc && typeof v.vsc.mark === "number") v.currentTime = v.vsc.mark;
if (v.vsc && typeof v.vsc.mark === "number") {
extendSpeedRestoreWindow(v);
v.currentTime = v.vsc.mark;
}
}
function handleDrag(video, e) {
const c = video.vsc.div;
const sC = c.shadowRoot.querySelector("#controller");
const sC = convertControllerToManualPosition(video.vsc);
if (!sC) return;
var pE = c.parentElement;
while (
pE.parentNode &&
@@ -958,9 +2470,16 @@ function handleDrag(video, e) {
const iXY = [e.clientX, e.clientY],
iCXY = [parseInt(sC.style.left), parseInt(sC.style.top)];
const sD = (e) => {
let s = sC.style;
s.left = iCXY[0] + e.clientX - iXY[0] + "px";
s.top = iCXY[1] + e.clientY - iXY[1] + "px";
sC.style.setProperty(
"left",
iCXY[0] + e.clientX - iXY[0] + "px",
"important"
);
sC.style.setProperty(
"top",
iCXY[1] + e.clientY - iXY[1] + "px",
"important"
);
};
const eD = () => {
pE.removeEventListener("mousemove", sD);
@@ -973,13 +2492,39 @@ function handleDrag(video, e) {
pE.addEventListener("mouseleave", eD);
pE.addEventListener("mousemove", sD);
}
var timer = null;
function showController(controller) {
function showController(controller, duration = 2000, forced = false) {
if (!controller || typeof controller.classList === "undefined") return;
var restoreHidden =
controller.restoreHiddenAfterShow === true ||
controller.classList.contains("vsc-hidden");
controller.restoreHiddenAfterShow = restoreHidden;
controller.classList.remove("vsc-hidden");
controller.classList.add("vsc-show");
if (timer) clearTimeout(timer);
timer = setTimeout(function () {
if (forced) {
controller.classList.add("vsc-forced-show");
}
if (controller.showTimeOut !== undefined) {
clearTimeout(controller.showTimeOut);
}
controller.showTimeOut = setTimeout(function () {
controller.classList.remove("vsc-show");
timer = false;
}, 2000);
controller.classList.remove("vsc-forced-show");
if (controller.restoreHiddenAfterShow === true) {
controller.classList.add("vsc-hidden");
}
controller.restoreHiddenAfterShow = false;
controller.showTimeOut = undefined;
}, duration);
}
// Add global listener to handle fullscreen transitions and adjust controller positions
document.addEventListener("fullscreenchange", () => {
tc.mediaElements.forEach((video) => {
if (video.vsc) {
applyControllerLocation(video.vsc, video.vsc.controllerLocation);
}
});
});
+34 -13
View File
@@ -1,13 +1,18 @@
{
"name": "Video Speed Controller",
"short_name": "videospeed",
"version": "1.4.5",
"name": "Speeder",
"short_name": "Speeder",
"version": "5.0.0",
"manifest_version": 2,
"description": "Speed up, slow down, advance and rewind HTML5 audio/video with shortcuts",
"homepage_url": "https://github.com/SoPat712/videospeed",
"description": "Speed up, slow down, advance and rewind HTML5 audio/video with shortcuts (New and improved version of \"Video Speed Controller\")",
"homepage_url": "https://github.com/SoPat712/speeder",
"browser_specific_settings": {
"gecko": {
"id": "{ed860648-f54f-4dc9-9a0d-501aec4313f5}"
"id": "{ed860648-f54f-4dc9-9a0d-501aec4313f5}",
"data_collection_permissions": {
"required": [
"none"
]
}
}
},
"icons": {
@@ -15,10 +20,15 @@
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"permissions": ["storage"],
"background": {
"scripts": ["background.js"]
},
"permissions": [
"storage"
],
"options_ui": {
"page": "options.html",
"open_in_tab": true
"open_in_tab": false
},
"browser_action": {
"default_icon": {
@@ -31,16 +41,27 @@
"content_scripts": [
{
"all_frames": true,
"matches": ["http://*/*", "https://*/*", "file:///*"],
"matches": [
"http://*/*",
"https://*/*",
"file:///*"
],
"match_about_blank": true,
"exclude_matches": [
"https://plus.google.com/hangouts/*",
"https://hangouts.google.com/*",
"https://meet.google.com/*"
],
"css": ["inject.css"],
"js": ["inject.js"]
"css": [
"inject.css"
],
"js": [
"inject.js"
]
}
],
"web_accessible_resources": ["inject.css", "shadow.css"]
}
"web_accessible_resources": [
"inject.css",
"shadow.css"
]
}
+621 -83
View File
@@ -1,112 +1,650 @@
:root {
--bg: #f4f5f7;
--panel: #ffffff;
--panel-subtle: #fafbfc;
--border: #e2e5e9;
--border-strong: #d4d9e0;
--text: #17191c;
--muted: #626b76;
--accent: #111827;
--danger: #b42318;
}
* {
box-sizing: border-box;
}
html {
min-height: 100%;
}
body {
margin: 0;
padding-left: 15px;
padding-top: 53px;
font-family: sans-serif;
font-size: 12px;
color: rgb(48, 57, 66);
min-height: 100vh;
padding: 24px 16px 40px;
background: var(--bg);
color: var(--text);
font: 14px/1.45 "Avenir Next", "SF Pro Text", "Segoe UI", sans-serif;
}
.page-shell {
width: min(880px, 100%);
margin: 0 auto;
}
.page-header {
margin-bottom: 10px;
}
.title-row {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
}
.title-block {
max-width: 560px;
}
h1,
h2,
h3 {
font-weight: normal;
line-height: 1;
user-select: none;
cursor: default;
}
h1 {
font-size: 1.5em;
margin: 21px 0 13px;
}
h3 {
font-size: 1.2em;
margin-bottom: 0.8em;
color: black;
}
p {
margin: 0.65em 0;
h3,
h4 {
margin: 0;
font-family: "Avenir Next", "SF Pro Display", "Segoe UI", sans-serif;
font-weight: 600;
letter-spacing: -0.01em;
}
header {
position: fixed;
top: 0;
left: 15px;
right: 0;
border-bottom: 1px solid #eee;
background: linear-gradient(white, white 40%, rgba(255, 255, 255, 0.92));
h1 {
font-size: 28px;
line-height: 1.1;
}
header,
section {
min-width: 600px;
max-width: 738px;
h3 {
font-size: 16px;
line-height: 1.25;
}
section {
padding-left: 18px;
margin-top: 8px;
margin-bottom: 24px;
h4 {
font-size: 15px;
line-height: 1.3;
}
section h3 {
margin-left: -18px;
.page-subtitle,
.section-intro {
margin: 6px 0 0;
color: var(--muted);
font-size: 13px;
}
.version {
display: inline-flex;
align-items: center;
min-height: 26px;
padding: 0 9px;
border: 1px solid var(--border);
border-radius: 999px;
background: var(--panel);
color: var(--muted);
font-size: 12px;
font-weight: 600;
}
.settings-stack {
display: grid;
gap: 10px;
}
.settings-card {
padding: 18px;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--panel);
}
.section-heading {
margin-bottom: 10px;
}
.defaults-divider {
height: 1px;
background: var(--border);
margin: 14px 0 10px;
}
.defaults-sub-heading {
font-size: 13px;
font-weight: 600;
color: var(--muted);
margin-bottom: 8px;
}
p {
margin: 0.75em 0;
}
a,
a:visited {
color: var(--text);
text-decoration-color: #c6ccd5;
text-underline-offset: 0.14em;
}
a:hover,
a:focus {
color: #000;
}
code {
padding: 0.08em 0.38em;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--panel-subtle);
font-family: "SFMono-Regular", Menlo, Consolas, monospace;
font-size: 0.92em;
}
button,
input,
select,
textarea {
font: inherit;
}
button {
-webkit-appearance: none;
position: relative;
margin: 0 1px 0 0;
padding: 0 10px;
min-width: 4em;
min-height: 2em;
background-image: linear-gradient(#ededed, #ededed 38%, #dedede);
border: 1px solid rgba(0, 0, 0, 0.25);
border-radius: 2px;
outline: none;
box-shadow: 0 1px 0 rgba(0, 0, 0, 0.08),
inset 0 1px 2px rgba(255, 255, 255, 0.75);
color: #444;
text-shadow: 0 1px 0 rgb(240, 240, 240);
font: inherit;
user-select: none;
appearance: none;
min-height: 36px;
padding: 0 14px;
border: 1px solid var(--border-strong);
border-radius: 10px;
background: var(--panel);
color: var(--text);
font-weight: 500;
cursor: pointer;
transition: background-color 120ms ease, border-color 120ms ease;
}
input[type="text"] {
width: 75px;
text-align: center;
button:hover {
background: #f8f9fb;
border-color: #c5ccd5;
}
.row {
margin: 5px 0px;
button:active {
background: #f1f3f5;
}
button:focus-visible,
input[type="text"]:focus,
select:focus,
textarea:focus {
outline: 2px solid rgba(17, 24, 39, 0.14);
outline-offset: 2px;
}
#save {
background: var(--accent);
border-color: var(--accent);
color: #fff;
}
#save:hover {
background: #1f2937;
border-color: #1f2937;
}
input[type="text"],
select,
textarea {
width: 100%;
min-height: 36px;
padding: 8px 10px;
border: 1px solid var(--border-strong);
border-radius: 10px;
background: var(--panel);
color: var(--text);
}
input[type="text"]:focus,
select:focus,
textarea:focus {
border-color: #9ca3af;
}
input[type="checkbox"] {
width: 16px;
height: 16px;
margin: 2px 0 0;
accent-color: var(--accent);
}
label {
display: inline-block;
width: 170px;
vertical-align: top;
display: block;
}
label em {
display: block;
margin-top: 4px;
color: var(--muted);
font-style: normal;
}
.shortcuts-grid {
display: flex;
flex-direction: column;
}
.shortcut-row {
display: grid;
grid-template-columns: minmax(0, 1fr) 120px 120px;
gap: 12px;
align-items: center;
padding: 10px 0;
border-top: 1px solid var(--border);
}
.shortcuts-grid .shortcut-row:first-child {
padding-top: 0;
border-top: 0;
}
.shortcut-row.customs {
grid-template-columns: minmax(0, 1fr) 120px 120px 38px;
}
.shortcut-label {
color: var(--text);
font-weight: 500;
}
.customKey,
.customValue {
text-align: center;
}
#addShortcutSelector {
width: min(220px, 100%);
margin-top: 12px;
}
.removeParent,
.toggle-site-rule {
display: inline-flex;
align-items: center;
justify-content: center;
width: 36px;
min-width: 36px;
height: 36px;
padding: 0;
font-size: 18px;
line-height: 1;
}
.removeParent {
color: var(--danger);
font-weight: 500;
}
.toggle-site-rule {
font-weight: 400;
}
.row {
display: grid;
grid-template-columns: minmax(0, 1fr) 160px;
gap: 16px;
align-items: start;
padding: 10px 0;
border-top: 1px solid var(--border);
}
.settings-card .row:first-of-type {
padding-top: 0;
border-top: 0;
}
.cb-editor {
display: flex;
flex-direction: column;
gap: 16px;
}
.cb-editor-disabled {
opacity: 0.4;
pointer-events: none;
user-select: none;
}
.cb-zone-label {
font-size: 11px;
font-weight: 600;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.05em;
margin-bottom: 8px;
}
.cb-dropzone {
display: flex;
flex-wrap: wrap;
gap: 8px;
min-height: 52px;
padding: 10px;
border: 2px dashed var(--border);
border-radius: 10px;
background: var(--panel-subtle);
transition: border-color 150ms ease, background 150ms ease;
}
.cb-dropzone.cb-over {
border-color: var(--accent);
background: rgba(17, 24, 39, 0.03);
}
.cb-active-zone:empty::after {
content: "Drag buttons here";
display: flex;
align-items: center;
width: 100%;
justify-content: center;
color: var(--muted);
font-size: 13px;
font-style: italic;
}
.cb-available-zone:empty::after {
content: "All buttons active";
display: flex;
align-items: center;
width: 100%;
justify-content: center;
color: var(--muted);
font-size: 13px;
font-style: italic;
}
.cb-block {
display: flex;
align-items: center;
gap: 8px;
padding: 7px 12px 7px 8px;
border: 1px solid var(--border-strong);
border-radius: 8px;
background: var(--panel);
cursor: grab;
user-select: none;
transition: box-shadow 150ms ease, opacity 150ms ease;
}
.cb-block:hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}
.cb-block:active {
cursor: grabbing;
}
.cb-block.cb-dragging {
opacity: 0.35;
}
.cb-grip {
width: 6px;
min-width: 6px;
height: 14px;
background-image: radial-gradient(circle, currentColor 1px, transparent 1px);
background-size: 3px 3px;
opacity: 0.35;
}
.cb-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
border-radius: 4px;
background: var(--panel-subtle);
border: 1px solid var(--border);
font-size: 12px;
line-height: 1;
}
.cb-label {
font-size: 13px;
font-weight: 500;
white-space: nowrap;
}
#siteRulesContainer {
display: grid;
gap: 12px;
margin-bottom: 12px;
}
.site-rule {
padding: 12px;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--panel-subtle);
}
.site-rule-header {
display: grid;
grid-template-columns: 36px minmax(0, 1fr) auto;
gap: 10px;
align-items: center;
}
.site-pattern {
min-width: 0;
font-family: "SFMono-Regular", Menlo, Consolas, monospace;
}
.site-rule-body {
margin-top: 12px;
}
.site-rule-content.disabled-rule {
opacity: 0.55;
pointer-events: none;
}
.site-rule-option {
display: grid;
grid-template-columns: minmax(0, 1fr) 150px;
gap: 16px;
align-items: start;
padding: 8px 0;
border-top: 1px solid var(--border);
}
.site-rule-body > .site-rule-option:first-child,
.site-rule-content > .site-rule-option:first-child {
padding-top: 0;
border-top: 0;
}
.site-rule-option label {
display: flex;
align-items: flex-start;
gap: 10px;
width: auto;
}
.site-rule-controlbar,
.site-rule-shortcuts {
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid var(--border);
}
.site-rule-controlbar > label,
.site-rule-shortcuts > label {
display: flex;
align-items: flex-start;
gap: 10px;
width: auto;
margin: 0;
}
.site-controlbar-container,
.site-popup-controlbar-container {
margin-top: 12px;
}
.site-shortcuts-container {
display: flex;
flex-direction: column;
gap: 10px;
margin-top: 12px;
}
.site-shortcuts-container .shortcut-row {
grid-template-columns: minmax(0, 1fr) 110px 110px minmax(0, 1fr);
padding: 8px 0;
border-top: 1px solid var(--border);
}
.site-shortcuts-container .shortcut-row:first-child {
padding-top: 0;
border-top: 0;
}
.force-label {
display: flex;
align-items: flex-start;
gap: 8px;
width: auto;
margin: 0;
color: var(--muted);
font-size: 12px;
}
.force-label input {
margin-top: 2px;
}
.action-row {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
#status {
color: #9d9d9d;
display: inline-block;
margin-left: 50px;
min-height: 1.3em;
margin-top: 10px;
color: var(--muted);
font-weight: 500;
}
#faq {
margin-top: 2em;
}
select {
width: 170px;
}
.customForce {
#status:empty {
display: none;
width: 250px;
}
.customKey {
color: transparent;
text-shadow: 0 0 0 #000000;
#faq hr {
height: 1px;
margin: 0 0 14px;
border: 0;
background: var(--border);
}
.support-footer {
padding: 16px 20px;
color: var(--muted);
}
.support-footer p {
margin: 0;
}
.support-footer a {
font-weight: 600;
}
@media (max-width: 720px) {
.shortcut-row,
.shortcut-row.customs,
.row,
.site-rule-option,
.site-shortcuts-container .shortcut-row {
grid-template-columns: 1fr;
}
.action-row button,
#addShortcutSelector {
width: 100%;
}
.site-rule-header {
grid-template-columns: 36px minmax(0, 1fr);
}
.remove-site-rule {
grid-column: 1 / -1;
}
}
@media (max-width: 520px) {
body {
padding: 16px 12px 28px;
}
h1 {
font-size: 24px;
}
.settings-card {
padding: 16px;
}
.site-rule-header {
grid-template-columns: 1fr;
}
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #111315;
--panel: #171a1d;
--panel-subtle: #1b1f23;
--border: #2b3138;
--border-strong: #3a414a;
--text: #f2f4f6;
--muted: #a0a8b2;
--accent: #f2f4f6;
--danger: #ff8a80;
}
body {
color-scheme: dark;
}
a,
a:visited {
color: #f2f4f6;
text-decoration-color: #4b5563;
}
#save {
background: #f2f4f6;
border-color: #f2f4f6;
color: #111315;
}
#save:hover {
background: #dfe3e8;
border-color: #dfe3e8;
}
.cb-dropzone.cb-over {
background: rgba(255, 255, 255, 0.04);
}
input[type="text"]:focus,
select:focus,
textarea:focus {
border-color: #6b7280;
}
}
+512 -226
View File
@@ -1,244 +1,530 @@
<!doctype html>
<html>
<head>
<title>Video Speed Controller: Options</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Speeder Settings</title>
<link rel="stylesheet" href="options.css" />
<script src="options.js"></script>
<script src="importExport.js"></script>
</head>
<body>
<header>
<h1>Video Speed Controller</h1>
</header>
<div class="page-shell">
<header class="page-header">
<div class="title-row">
<div class="title-block">
<h1>Speeder settings</h1>
<p class="page-subtitle">Shortcuts, defaults, and site rules.</p>
</div>
<div class="version">v<span id="app-version"></span></div>
</div>
</header>
<section id="customs">
<h3>Shortcuts</h3>
<div class="row customs" id="display">
<select class="customDo">
<option value="display">Show/hide controller</option>
</select>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input class="customValue" type="text" placeholder="value (0.10)" />
<select class="customForce">
<option value="false">Do not disable website key bindings</option>
<option value="true">Disable website key bindings</option>
</select>
</div>
<div class="row customs" id="slower">
<select class="customDo">
<option value="slower">Decrease speed</option>
</select>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input class="customValue" type="text" placeholder="value (0.10)" />
<select class="customForce">
<option value="false">Do not disable website key bindings</option>
<option value="true">Disable website key bindings</option>
</select>
</div>
<div class="row customs" id="faster">
<select class="customDo">
<option value="faster">Increase speed</option>
</select>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input class="customValue" type="text" placeholder="value (0.10)" />
<select class="customForce">
<option value="false">Do not disable website key bindings</option>
<option value="true">Disable website key bindings</option>
</select>
</div>
<div class="row customs" id="rewind">
<select class="customDo">
<option value="rewind">Rewind</option>
</select>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input class="customValue" type="text" placeholder="value (10)" />
<select class="customForce">
<option value="false">Do not disable website key bindings</option>
<option value="true">Disable website key bindings</option>
</select>
</div>
<div class="row customs" id="advance">
<select class="customDo">
<option value="advance">Advance</option>
</select>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input class="customValue" type="text" placeholder="value (10)" />
<select class="customForce">
<option value="false">Do not disable website key bindings</option>
<option value="true">Disable website key bindings</option>
</select>
</div>
<div class="row customs" id="reset">
<select class="customDo">
<option value="reset">Reset speed</option>
</select>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value (1.00)"
disabled
/>
<select class="customForce">
<option value="false">Do not disable website key bindings</option>
<option value="true">Disable website key bindings</option>
</select>
</div>
<div class="row customs" id="fast">
<select class="customDo">
<option value="fast">Preferred speed</option>
</select>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input class="customValue" type="text" placeholder="value (1.80)" />
<select class="customForce">
<option value="false">Do not disable website key bindings</option>
<option value="true">Disable website key bindings</option>
</select>
</div>
<main class="settings-stack">
<section id="customs" class="settings-card">
<div class="section-heading">
<h3>Shortcuts</h3>
<p class="section-intro">Backspace clears a shortcut. Escape disables it.</p>
</div>
<div class="shortcuts-grid">
<div class="shortcut-row" id="display" data-action="display">
<div class="shortcut-label">Show/hide controller</div>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value"
value="N/A"
disabled
/>
</div>
<div class="shortcut-row" id="move" data-action="move">
<div class="shortcut-label">Move controller</div>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value"
value="N/A"
disabled
/>
</div>
<div class="shortcut-row" id="slower" data-action="slower">
<div class="shortcut-label">Decrease speed</div>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value (0.10)"
/>
</div>
<div class="shortcut-row" id="faster" data-action="faster">
<div class="shortcut-label">Increase speed</div>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value (0.10)"
/>
</div>
<div class="shortcut-row" id="rewind" data-action="rewind">
<div class="shortcut-label">Rewind</div>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value (10)"
/>
</div>
<div class="shortcut-row" id="advance" data-action="advance">
<div class="shortcut-label">Advance</div>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value (10)"
/>
</div>
<div class="shortcut-row" id="reset" data-action="reset">
<div class="shortcut-label">Reset speed</div>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value"
value="N/A"
disabled
/>
</div>
<div class="shortcut-row" id="fast" data-action="fast">
<div class="shortcut-label">Preferred speed</div>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value (1.80)"
/>
</div>
<div
class="shortcut-row"
id="toggleSubtitleNudge"
data-action="toggleSubtitleNudge"
>
<div class="shortcut-label">Toggle subtitle nudge</div>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value"
value="N/A"
disabled
/>
</div>
</div>
<button id="add">Add New</button>
</section>
<select id="addShortcutSelector">
<option value="">Add shortcut&hellip;</option>
</select>
</section>
<section>
<h3>Other</h3>
<div class="row">
<label for="enabled">Enable</label>
<input id="enabled" type="checkbox" />
</div>
<div class="row">
<label for="startHidden">Hide controller by default</label>
<input id="startHidden" type="checkbox" />
</div>
<div class="row">
<label for="rememberSpeed">Remember playback speed</label>
<input id="rememberSpeed" type="checkbox" />
</div>
<div class="row">
<label for="forceLastSavedSpeed"
>Force last saved speed<br />
<em
>Useful for video players that override the speeds set by
VideoSpeed</em
></label
>
<input id="forceLastSavedSpeed" type="checkbox" />
</div>
<div class="row">
<label for="audioBoolean">Work on audio</label>
<input id="audioBoolean" type="checkbox" />
</div>
<div class="row">
<label for="controllerOpacity">Controller opacity</label>
<input id="controllerOpacity" type="text" value="" />
</div>
<div class="row">
<label for="blacklist"
>Sites on which extension is disabled<br />
(one per line)<br />
<br />
<em>
<a href="https://www.regexpal.com/">Regex</a> is supported.<br />
Be sure it is in "//g" format.<br />
ie: /(.+)youtube\.com(\/*)$/gi
</em>
</label>
<textarea id="blacklist" rows="10" cols="50"></textarea>
</div>
</section>
<section id="generalSettings" class="settings-card">
<div class="section-heading">
<h3>Defaults</h3>
<p class="section-intro">Used unless a site rule overrides it.</p>
</div>
<section id="nudgeSettings">
<h3>Subtitle Nudge Settings (Experimental - YouTube Only)</h3>
<div class="row">
<label for="enableSubtitleNudge"
>Enable Subtitle Nudge <br /><em
>Periodically 'nudges' video speed by a tiny amount to help keep
subtitles in sync on some sites (e.g. YouTube).</em
>
</label>
<input id="enableSubtitleNudge" type="checkbox" />
</div>
<div class="row">
<label for="subtitleNudgeInterval"
>Nudge Interval (milliseconds) <br /><em
>How often to nudge (e.g., 25-1000). Smaller values are more
frequent. Default: 25.</em
>
</label>
<input
id="subtitleNudgeInterval"
type="text"
value=""
placeholder="25"
/>
</div>
<div class="row">
<label for="subtitleNudgeAmount"
>Nudge Amount (decimal) <br /><em
>How much to change speed by (e.g., 0.001). Very small values
recommended. Default: 0.001.</em
>
</label>
<input
id="subtitleNudgeAmount"
type="text"
value=""
placeholder="0.001"
/>
</div>
</section>
<h4 class="defaults-sub-heading">General</h4>
<button id="save">Save</button>
<button id="restore">Restore Defaults</button>
<button id="experimental">Show Experimental Features</button>
<div class="row">
<label for="enabled">Enable</label>
<input id="enabled" type="checkbox" />
</div>
<div class="row">
<label for="audioBoolean">Work on audio</label>
<input id="audioBoolean" type="checkbox" />
</div>
<div id="status"></div>
<div class="defaults-divider"></div>
<h4 class="defaults-sub-heading">Playback</h4>
<div id="faq">
<hr />
<div class="row">
<label for="rememberSpeed">Remember playback speed</label>
<input id="rememberSpeed" type="checkbox" />
</div>
<div class="row">
<label for="forceLastSavedSpeed"
>Force last saved speed<br />
<em
>Useful when a video player tries to override the speed you set
in Speeder.</em
>
</label>
<input id="forceLastSavedSpeed" type="checkbox" />
</div>
<h4>Extension controls not appearing?</h4>
<p>
This extension is only compatible with HTML5 audio and video. If you
don't see the controls showing up, chances are you are viewing a Flash
content. If you want to confirm, try right-clicking on the content and
inspect the menu: if it mentions flash, then that's the issue. That
said, <b>most sites will fallback to HTML5</b> if they detect that Flash
is not available. You can try manually disabling Flash from the browser.
</p>
<div class="defaults-divider"></div>
<h4 class="defaults-sub-heading">Controller</h4>
<div class="row">
<label for="startHidden">Hide controller by default</label>
<input id="startHidden" type="checkbox" />
</div>
<div class="row">
<label for="controllerLocation">Default controller location</label>
<select id="controllerLocation">
<option value="top-left">Top left</option>
<option value="top-center">Top center</option>
<option value="top-right">Top right</option>
<option value="middle-right">Middle right</option>
<option value="bottom-right">Bottom right</option>
<option value="bottom-center">Bottom center</option>
<option value="bottom-left">Bottom left</option>
<option value="middle-left">Middle left</option>
</select>
</div>
<div class="row">
<label for="controllerOpacity">Controller opacity</label>
<input id="controllerOpacity" type="text" value="" />
</div>
<div class="row">
<label for="hideWithControls"
>Hide with controls<br />
<em
>Fade the controller in and out with the video interface:
perfect sync on YouTube, idle-based elsewhere.</em
>
</label>
<input id="hideWithControls" type="checkbox" />
</div>
<div class="row">
<label for="hideWithControlsTimer"
>Auto-hide timer (seconds)<br />
<em
>Seconds of inactivity before hiding: 0.1&ndash;15 for
non-YouTube sites.</em
>
</label>
<input id="hideWithControlsTimer" type="text" placeholder="2" />
</div>
<div class="row">
<label for="showPopupControlBar">Show popup control bar</label>
<input id="showPopupControlBar" type="checkbox" />
</div>
<div class="defaults-divider"></div>
<h4 class="defaults-sub-heading">Subtitle sync</h4>
<div class="row">
<label for="enableSubtitleNudge"
>Enable subtitle nudge<br /><em
>Makes tiny playback changes to help keep subtitles aligned.</em
>
</label>
<input id="enableSubtitleNudge" type="checkbox" />
</div>
<div class="row">
<label for="subtitleNudgeInterval"
>Nudge interval (milliseconds)<br /><em
>How often to nudge: 10&ndash;1000. Smaller values are more
frequent. Default: 50.</em
>
</label>
<input
id="subtitleNudgeInterval"
type="text"
value=""
placeholder="50"
/>
</div>
</section>
<section id="controlBarSettings" class="settings-card">
<div class="section-heading">
<h3>Control bar</h3>
<p class="section-intro">
Drag blocks to reorder. Move between Active and Available to show
or hide buttons.
</p>
</div>
<div class="cb-editor">
<div class="cb-zone">
<div class="cb-zone-label">Active</div>
<div
id="controlBarActive"
class="cb-dropzone cb-active-zone"
></div>
</div>
<div class="cb-zone">
<div class="cb-zone-label">Available</div>
<div
id="controlBarAvailable"
class="cb-dropzone cb-available-zone"
></div>
</div>
</div>
</section>
<section id="popupControlBarSettings" class="settings-card">
<div class="section-heading">
<h3>Popup control bar</h3>
<p class="section-intro">
Configure which buttons appear in the browser popup control bar.
</p>
</div>
<div class="row">
<label for="popupMatchHoverControls">Match hover controls</label>
<input id="popupMatchHoverControls" type="checkbox" />
</div>
<div id="popupCbEditorWrap" class="cb-editor cb-editor-disabled">
<div class="cb-zone">
<div class="cb-zone-label">Active</div>
<div
id="popupControlBarActive"
class="cb-dropzone cb-active-zone"
></div>
</div>
<div class="cb-zone">
<div class="cb-zone-label">Available</div>
<div
id="popupControlBarAvailable"
class="cb-dropzone cb-available-zone"
></div>
</div>
</div>
</section>
<section id="siteRules" class="settings-card">
<div class="section-heading">
<h3>Site rules</h3>
<p class="section-intro">
Use plain domains or
<a
href="https://www.regexpal.com/"
target="_blank"
rel="noopener noreferrer"
>Regex</a
>
patterns like <code>/(.+)youtube\.com(\/*)$/gi</code>.
</p>
</div>
<div id="siteRulesContainer"></div>
<button id="addSiteRule" type="button">Add Site Rule</button>
</section>
<template id="siteRuleTemplate">
<div class="site-rule">
<div class="site-rule-header">
<button type="button" class="toggle-site-rule" title="Expand/Collapse">&plus;</button>
<input
type="text"
class="site-pattern"
placeholder="e.g., youtube.com or /regex/gi"
/>
<button type="button" class="remove-site-rule">Remove</button>
</div>
<div class="site-rule-body">
<div class="site-rule-option">
<label>
<input type="checkbox" class="site-enabled" />
Enable Speeder on this site
</label>
</div>
<div class="site-rule-content">
<div class="site-rule-option">
<label>Hide controller by default:</label>
<input type="checkbox" class="site-startHidden" />
</div>
<div class="site-rule-option">
<label>
<input type="checkbox" class="site-hideWithControls" />
Hide with controls (idle-based)
</label>
</div>
<div class="site-rule-option">
<label>Auto-hide timer (0.1&ndash;15s):</label>
<input type="text" class="site-hideWithControlsTimer" />
</div>
<div class="site-rule-option">
<label>Default controller location:</label>
<select class="site-controllerLocation">
<option value="top-left">Top left</option>
<option value="top-center">Top center</option>
<option value="top-right">Top right</option>
<option value="middle-right">Middle right</option>
<option value="bottom-right">Bottom right</option>
<option value="bottom-center">Bottom center</option>
<option value="bottom-left">Bottom left</option>
<option value="middle-left">Middle left</option>
</select>
</div>
<div class="site-rule-option">
<label>Remember playback speed:</label>
<input type="checkbox" class="site-rememberSpeed" />
</div>
<div class="site-rule-option">
<label>Force last saved speed:</label>
<input type="checkbox" class="site-forceLastSavedSpeed" />
</div>
<div class="site-rule-option">
<label>Work on audio:</label>
<input type="checkbox" class="site-audioBoolean" />
</div>
<div class="site-rule-option">
<label>Controller opacity:</label>
<input type="text" class="site-controllerOpacity" />
</div>
<div class="site-rule-option">
<label>Show popup control bar:</label>
<input type="checkbox" class="site-showPopupControlBar" />
</div>
<div class="site-rule-option">
<label>Enable subtitle nudge:</label>
<input type="checkbox" class="site-enableSubtitleNudge" />
</div>
<div class="site-rule-option">
<label>Nudge interval (10&ndash;1000ms):</label>
<input type="text" class="site-subtitleNudgeInterval" placeholder="50" />
</div>
<div class="site-rule-controlbar">
<label>
<input type="checkbox" class="override-controlbar" />
Custom control bar for this site
</label>
<div class="site-controlbar-container" style="display: none">
<div class="cb-editor">
<div class="cb-zone">
<div class="cb-zone-label">Active</div>
<div class="cb-dropzone cb-active-zone site-cb-active"></div>
</div>
<div class="cb-zone">
<div class="cb-zone-label">Available</div>
<div class="cb-dropzone cb-available-zone site-cb-available"></div>
</div>
</div>
</div>
</div>
<div class="site-rule-controlbar">
<label>
<input type="checkbox" class="override-popup-controlbar" />
Custom popup control bar for this site
</label>
<div class="site-popup-controlbar-container" style="display: none">
<div class="cb-editor">
<div class="cb-zone">
<div class="cb-zone-label">Active</div>
<div class="cb-dropzone cb-active-zone site-popup-cb-active"></div>
</div>
<div class="cb-zone">
<div class="cb-zone-label">Available</div>
<div class="cb-dropzone cb-available-zone site-popup-cb-available"></div>
</div>
</div>
</div>
</div>
<div class="site-rule-shortcuts">
<label>
<input type="checkbox" class="override-shortcuts" />
Custom shortcuts for this site
</label>
<div class="site-shortcuts-container" style="display: none"></div>
</div>
</div>
</div>
</div>
</template>
<section class="settings-card action-card">
<div class="section-heading">
<h3>Actions</h3>
<p class="section-intro">Save, restore, export, or import settings.</p>
</div>
<div class="action-row">
<button id="save">Save Changes</button>
<button id="restore">Restore Defaults</button>
<button id="exportSettings">Export Settings</button>
<button id="importSettings">Import Settings</button>
</div>
<div id="status" role="status" aria-live="polite"></div>
</section>
<section id="faq" class="settings-card info-card">
<hr />
<h4>Extension controls not appearing?</h4>
<p>
This extension only works with HTML5 audio and video. If the
controls never appear, you may be looking at Flash content instead.
Right-click the player to check: if the menu mentions Flash, that
is the issue. Most sites will fall back to HTML5 when Flash is not
available, so disabling Flash in the browser can help.
</p>
</section>
<footer class="support-footer settings-card">
<p>
If Speeder has been useful, consider supporting its development via
<a
href="https://github.com/sponsors/SoPat712"
target="_blank"
rel="noopener noreferrer"
>GitHub Sponsor</a
>
or
<a
href="https://ko-fi.com/joshpatra"
target="_blank"
rel="noopener noreferrer"
>Ko-Fi</a
>.
</p>
</footer>
</main>
</div>
</body>
</html>
+1280 -250
View File
@@ -1,38 +1,9 @@
var regStrip = /^[\r\t\f\v ]+|[\r\t\f\v ]+$/gm;
var tcDefaults = {
speed: 1.0, // default:
displayKeyCode: 86, // default: V
rememberSpeed: false, // default: false
audioBoolean: false, // default: false
startHidden: false, // default: false
forceLastSavedSpeed: false, //default: false
enabled: true, // default enabled
controllerOpacity: 0.3, // default: 0.3
keyBindings: [
{ action: "display", key: 86, value: 0, force: false, predefined: true }, // V
{ action: "slower", key: 83, value: 0.1, force: false, predefined: true }, // S
{ action: "faster", key: 68, value: 0.1, force: false, predefined: true }, // D
{ action: "rewind", key: 90, value: 10, force: false, predefined: true }, // Z
{ action: "advance", key: 88, value: 10, force: false, predefined: true }, // X
{ action: "reset", key: 82, value: 1, force: false, predefined: true }, // R
{ action: "fast", key: 71, value: 1.8, force: false, predefined: true } // G
],
blacklist: `www.instagram.com
twitter.com
imgur.com
teams.microsoft.com
`.replace(regStrip, ""),
// ADDED: Nudge defaults
enableSubtitleNudge: true,
subtitleNudgeInterval: 25,
subtitleNudgeAmount: 0.001
};
var keyBindings = []; // This is populated during save/restore
var keyBindings = [];
var keyCodeAliases = {
/* ... same as your original ... */ 0: "null",
0: "null",
null: "null",
undefined: "null",
32: "Space",
@@ -83,160 +54,1100 @@ var keyCodeAliases = {
173: "-"
};
function recordKeyPress(e) {
/* ... same as your original ... */
if (
(e.keyCode >= 48 && e.keyCode <= 57) ||
(e.keyCode >= 65 && e.keyCode <= 90) ||
keyCodeAliases[e.keyCode]
) {
e.target.value =
keyCodeAliases[e.keyCode] || String.fromCharCode(e.keyCode);
e.target.keyCode = e.keyCode;
e.preventDefault();
e.stopPropagation();
} else if (e.keyCode === 8) {
e.target.value = "";
} else if (e.keyCode === 27) {
e.target.value = "null";
e.target.keyCode = null;
}
}
function inputFilterNumbersOnly(e) {
/* ... same as your original ... */
var char = String.fromCharCode(e.keyCode);
if (!/[\d\.]$/.test(char) || !/^\d+(\.\d*)?$/.test(e.target.value + char)) {
e.preventDefault();
e.stopPropagation();
}
}
function inputFocus(e) {
/* ... same as your original ... */ e.target.value = "";
}
function inputBlur(e) {
/* ... same as your original ... */ e.target.value =
keyCodeAliases[e.target.keyCode] || String.fromCharCode(e.target.keyCode);
}
// function updateShortcutInputText(inputId, keyCode) { /* ... same as your original ... */ } // Not directly used in provided options.js logic flow
function updateCustomShortcutInputText(inputItem, keyCode) {
/* ... same as your original ... */ inputItem.value =
keyCodeAliases[keyCode] || String.fromCharCode(keyCode);
inputItem.keyCode = keyCode;
}
var customActionsNoValues = ["pause", "muted", "mark", "jump", "display"]; // Original
function add_shortcut() {
/* ... same as your original ... */
var html = `<select class="customDo"><option value="slower">Decrease speed</option><option value="faster">Increase speed</option><option value="rewind">Rewind</option><option value="advance">Advance</option><option value="reset">Reset speed</option><option value="fast">Preferred speed</option><option value="muted">Mute</option><option value="pause">Pause</option><option value="mark">Set marker</option><option value="jump">Jump to marker</option><option value="display">Show/hide controller</option></select><input class="customKey" type="text" placeholder="press a key"/><input class="customValue" type="text" placeholder="value (0.10)"/><select class="customForce"><option value="false">Do not disable website key bindings</option><option value="true">Disable website key bindings</option></select><button class="removeParent">X</button>`;
var div = document.createElement("div");
div.setAttribute("class", "row customs");
div.innerHTML = html;
var customs_element = document.getElementById("customs");
customs_element.insertBefore(
div,
customs_element.children[customs_element.childElementCount - 1]
);
}
function createKeyBindings(item) {
/* ... same as your original ... */
const action = item.querySelector(".customDo").value;
const key = item.querySelector(".customKey").keyCode;
const value = Number(item.querySelector(".customValue").value);
const force = item.querySelector(".customForce").value;
const predefined = !!item.id;
keyBindings.push({
var keyCodeToKey = {
32: " ",
37: "ArrowLeft",
38: "ArrowUp",
39: "ArrowRight",
40: "ArrowDown",
96: "0",
97: "1",
98: "2",
99: "3",
100: "4",
101: "5",
102: "6",
103: "7",
104: "8",
105: "9",
106: "*",
107: "+",
109: "-",
110: ".",
111: "/",
112: "F1",
113: "F2",
114: "F3",
115: "F4",
116: "F5",
117: "F6",
118: "F7",
119: "F8",
120: "F9",
121: "F10",
122: "F11",
123: "F12",
186: ";",
188: "<",
189: "-",
187: "+",
190: ">",
191: "/",
192: "~",
219: "[",
220: "\\",
221: "]",
222: "'",
59: ";",
61: "+",
173: "-"
};
var modifierKeys = new Set([
"Alt",
"AltGraph",
"Control",
"Fn",
"Hyper",
"Meta",
"OS",
"Shift"
]);
var displayKeyAliases = {
" ": "Space",
ArrowLeft: "Left",
ArrowUp: "Up",
ArrowRight: "Right",
ArrowDown: "Down"
};
var controllerLocations = [
"top-left",
"top-center",
"top-right",
"middle-right",
"bottom-right",
"bottom-center",
"bottom-left",
"middle-left"
];
var controllerButtonDefs = {
rewind: { icon: "\u00AB", name: "Rewind" },
slower: { icon: "\u2212", name: "Decrease speed" },
faster: { icon: "+", name: "Increase speed" },
advance: { icon: "\u00BB", name: "Advance" },
display: { icon: "\u00D7", name: "Close controller" },
reset: { icon: "\u21BA", name: "Reset speed" },
fast: { icon: "\u2605", name: "Preferred speed" },
nudge: { icon: "\u2713", name: "Subtitle nudge" },
settings: { icon: "\u2699", name: "Settings" },
pause: { icon: "\u23EF", name: "Pause / Play" },
muted: { icon: "M", name: "Mute / Unmute" },
mark: { icon: "\u2691", name: "Set marker" },
jump: { icon: "\u21E5", name: "Jump to marker" }
};
function createDefaultBinding(action, key, keyCode, value) {
return {
action: action,
key: key,
keyCode: keyCode,
value: value,
force: force,
predefined: predefined
force: false,
predefined: true
};
}
var tcDefaults = {
speed: 1.0,
lastSpeed: 1.0,
displayKeyCode: 86,
rememberSpeed: false,
audioBoolean: false,
startHidden: false,
hideWithYouTubeControls: false,
hideWithControls: false,
hideWithControlsTimer: 2.0,
controllerLocation: "top-left",
forceLastSavedSpeed: false,
enabled: true,
controllerOpacity: 0.3,
keyBindings: [
createDefaultBinding("display", "V", 86, 0),
createDefaultBinding("move", "P", 80, 0),
createDefaultBinding("slower", "S", 83, 0.1),
createDefaultBinding("faster", "D", 68, 0.1),
createDefaultBinding("rewind", "Z", 90, 10),
createDefaultBinding("advance", "X", 88, 10),
createDefaultBinding("reset", "R", 82, 1),
createDefaultBinding("fast", "G", 71, 1.8),
createDefaultBinding("toggleSubtitleNudge", "N", 78, 0)
],
siteRules: [
{ pattern: "youtube.com", enabled: true, enableSubtitleNudge: true },
{ pattern: "example1.com", enabled: false },
{ pattern: "/example2\\.com/i", enabled: false },
{ pattern: "/(example3|sample3)\\.com/gi", enabled: false }
],
controllerButtons: ["rewind", "slower", "faster", "advance", "display"],
showPopupControlBar: true,
popupMatchHoverControls: true,
popupControllerButtons: ["rewind", "slower", "faster", "advance", "display"],
enableSubtitleNudge: false,
subtitleNudgeInterval: 50,
subtitleNudgeAmount: 0.001
};
const actionLabels = {
display: "Show/hide controller",
move: "Move controller",
slower: "Decrease speed",
faster: "Increase speed",
rewind: "Rewind",
advance: "Advance",
reset: "Reset speed",
fast: "Preferred speed",
muted: "Mute",
pause: "Pause",
mark: "Set marker",
jump: "Jump to marker",
toggleSubtitleNudge: "Toggle subtitle nudge"
};
const customActionsNoValues = [
"reset",
"display",
"move",
"muted",
"pause",
"mark",
"jump",
"toggleSubtitleNudge"
];
function refreshAddShortcutSelector() {
const selector = document.getElementById("addShortcutSelector");
if (!selector) return;
// Clear existing options except the first one
while (selector.options.length > 1) {
selector.remove(1);
}
// Find all currently used actions
const usedActions = new Set();
document.querySelectorAll(".shortcut-row").forEach((row) => {
const action = row.dataset.action;
if (action) {
usedActions.add(action);
}
});
// Add all unused actions
Object.keys(actionLabels).forEach((action) => {
if (!usedActions.has(action)) {
const option = document.createElement("option");
option.value = action;
option.text = actionLabels[action];
selector.appendChild(option);
}
});
// If no available actions, hide or disable the selector
if (selector.options.length === 1) {
selector.disabled = true;
selector.options[0].text = "All shortcuts added";
} else {
selector.disabled = false;
selector.options[0].text = "Add shortcut\u2026";
}
}
function ensureDefaultBinding(storage, action, key, keyCode, value) {
if (storage.keyBindings.some((item) => item.action === action)) return;
storage.keyBindings.push(createDefaultBinding(action, key, keyCode, value));
}
function normalizeControllerLocation(location) {
if (controllerLocations.includes(location)) return location;
return tcDefaults.controllerLocation;
}
function normalizeBindingKey(key) {
if (typeof key !== "string" || key.length === 0) return null;
if (key === "Spacebar") return " ";
if (key === "Esc") return "Escape";
if (key.length === 1 && /[a-z]/i.test(key)) return key.toUpperCase();
return key;
}
function getLegacyKeyCode(binding) {
if (!binding) return null;
if (Number.isInteger(binding.keyCode)) return binding.keyCode;
if (typeof binding.key === "number" && Number.isInteger(binding.key)) {
return binding.key;
}
return null;
}
function legacyKeyCodeToBinding(keyCode) {
if (!Number.isInteger(keyCode)) return null;
var normalizedKey = keyCodeToKey[keyCode];
if (!normalizedKey && keyCode >= 48 && keyCode <= 57) {
normalizedKey = String.fromCharCode(keyCode);
}
if (!normalizedKey && keyCode >= 65 && keyCode <= 90) {
normalizedKey = String.fromCharCode(keyCode);
}
return {
key: normalizeBindingKey(normalizedKey),
keyCode: keyCode,
code: null,
disabled: false
};
}
function createDisabledBinding() {
return {
key: null,
keyCode: null,
code: null,
disabled: true
};
}
function normalizeStoredBinding(binding, fallbackKeyCode) {
var fallbackBinding = legacyKeyCodeToBinding(fallbackKeyCode);
if (!binding) {
return fallbackBinding;
}
if (
binding.disabled === true ||
(binding.key === null &&
binding.keyCode === null &&
binding.code === null)
) {
return createDisabledBinding();
}
var normalized = {
key: null,
keyCode: null,
code:
typeof binding.code === "string" && binding.code.length > 0
? binding.code
: null,
disabled: false
};
if (typeof binding.key === "string") {
normalized.key = normalizeBindingKey(binding.key);
}
var legacyKeyCode = getLegacyKeyCode(binding);
if (Number.isInteger(legacyKeyCode)) {
var legacyBinding = legacyKeyCodeToBinding(legacyKeyCode);
if (legacyBinding) {
normalized.key = normalized.key || legacyBinding.key;
normalized.keyCode = legacyKeyCode;
}
}
if (Number.isInteger(binding.keyCode)) {
normalized.keyCode = binding.keyCode;
}
if (!normalized.key && fallbackBinding) {
normalized.key = fallbackBinding.key;
if (normalized.keyCode === null) normalized.keyCode = fallbackBinding.keyCode;
}
if (!normalized.key && !normalized.code && normalized.keyCode === null) {
return null;
}
return normalized;
}
function getBindingLabel(binding) {
if (!binding) return "";
if (binding.disabled) return "";
if (binding.key) {
return displayKeyAliases[binding.key] || binding.key;
}
var legacyKeyCode = getLegacyKeyCode(binding);
if (keyCodeAliases[legacyKeyCode]) return keyCodeAliases[legacyKeyCode];
if (Number.isInteger(legacyKeyCode)) return String.fromCharCode(legacyKeyCode);
return "";
}
function setShortcutInputBinding(input, binding) {
input.vscBinding = binding ? Object.assign({}, binding) : null;
input.keyCode =
binding && Number.isInteger(binding.keyCode) ? binding.keyCode : null;
input.value = getBindingLabel(binding);
}
function captureBindingFromEvent(event) {
var normalizedKey = normalizeBindingKey(event.key);
if (!normalizedKey || modifierKeys.has(normalizedKey)) return null;
return {
key: normalizedKey,
keyCode: Number.isInteger(event.keyCode) ? event.keyCode : null,
code: event.code || null,
disabled: false
};
}
function recordKeyPress(event) {
if (event.key === "Tab") return;
if (event.key === "Backspace") {
setShortcutInputBinding(event.target, null);
event.preventDefault();
event.stopPropagation();
return;
}
if (event.key === "Escape") {
setShortcutInputBinding(event.target, createDisabledBinding());
event.preventDefault();
event.stopPropagation();
return;
}
var binding = captureBindingFromEvent(event);
if (!binding) return;
setShortcutInputBinding(event.target, binding);
event.preventDefault();
event.stopPropagation();
}
function inputFilterNumbersOnly(event) {
var char = String.fromCharCode(event.keyCode);
if (
!/[\d\.]$/.test(char) ||
!/^\d+(\.\d*)?$/.test(event.target.value + char)
) {
event.preventDefault();
event.stopPropagation();
}
}
function inputFocus(event) {
event.target.value = "";
}
function inputBlur(event) {
setShortcutInputBinding(event.target, event.target.vscBinding || null);
}
function updateCustomShortcutInputText(inputItem, bindingOrKeyCode) {
if (
bindingOrKeyCode &&
typeof bindingOrKeyCode === "object" &&
!Array.isArray(bindingOrKeyCode)
) {
setShortcutInputBinding(inputItem, bindingOrKeyCode);
return;
}
setShortcutInputBinding(inputItem, legacyKeyCodeToBinding(bindingOrKeyCode));
}
function appendSelectOptions(select, options) {
options.forEach(function (optionData) {
var option = document.createElement("option");
option.value = optionData.value;
option.textContent = optionData.label;
select.appendChild(option);
});
}
function add_shortcut(action, value) {
if (!action) return;
var div = document.createElement("div");
div.setAttribute("class", "shortcut-row customs");
div.dataset.action = action;
var actionLabel = document.createElement("div");
actionLabel.className = "shortcut-label";
actionLabel.textContent = actionLabels[action] || action;
var keyInput = document.createElement("input");
keyInput.className = "customKey";
keyInput.type = "text";
keyInput.placeholder = "press a key";
var valueInput = document.createElement("input");
valueInput.className = "customValue";
valueInput.type = "text";
valueInput.placeholder = "value";
if (customActionsNoValues.includes(action)) {
valueInput.value = "N/A";
valueInput.disabled = true;
} else {
valueInput.value = value || 0;
}
var removeButton = document.createElement("button");
removeButton.className = "removeParent";
removeButton.type = "button";
removeButton.textContent = "\u00d7";
div.appendChild(actionLabel);
div.appendChild(keyInput);
div.appendChild(valueInput);
div.appendChild(removeButton);
var customsElement = document.querySelector(".shortcuts-grid");
customsElement.appendChild(div);
refreshAddShortcutSelector();
}
function createKeyBindings(item) {
var action = item.dataset.action || item.querySelector(".customDo").value;
var input = item.querySelector(".customKey");
var valueInput = item.querySelector(".customValue");
var predefined = !!item.id;
var fallbackKeyCode =
predefined && action === "display"
? tcDefaults.displayKeyCode
: undefined;
var binding = normalizeStoredBinding(input.vscBinding, fallbackKeyCode);
if (!binding) {
return {
valid: false,
message: "Error: Shortcut for " + action + " is invalid. Unable to save"
};
}
keyBindings.push({
action: action,
key: binding.key,
keyCode: binding.keyCode,
code: binding.code,
disabled: binding.disabled === true,
value: customActionsNoValues.includes(action)
? 0
: Number(valueInput.value),
force: false,
predefined: predefined
});
return { valid: true };
}
function validate() {
/* ... same as your original ... */
var valid = true;
var status = document.getElementById("status");
document
.getElementById("blacklist")
.value.split("\n")
.forEach((match) => {
match = match.replace(regStrip, "");
if (match.startsWith("/")) {
try {
new RegExp(match);
} catch (err) {
status.textContent =
"Error: Invalid blacklist regex: " + match + ". Unable to save";
valid = false;
return;
// Validate site rules patterns
document.querySelectorAll(".site-rule").forEach((ruleEl) => {
var pattern = ruleEl.querySelector(".site-pattern").value.trim();
if (pattern.length === 0) return;
if (pattern.startsWith("/")) {
try {
var lastSlash = pattern.lastIndexOf("/");
if (lastSlash > 0) {
new RegExp(pattern.substring(1, lastSlash), pattern.substring(lastSlash + 1));
}
} catch (err) {
status.textContent =
"Error: Invalid site rule regex: " + pattern + ". Unable to save";
valid = false;
return;
}
});
}
});
return valid;
}
// MODIFIED: save_options to include nudge settings
function save_options() {
if (validate() === false) return;
keyBindings = []; // Reset global keyBindings before populating from DOM
Array.from(document.querySelectorAll(".customs")).forEach((item) =>
createKeyBindings(item)
keyBindings = [];
var status = document.getElementById("status");
var saveError = null;
// Collect shortcuts from the main shortcuts section (both default and custom)
Array.from(document.querySelectorAll("#customs .shortcut-row")).forEach((item) => {
if (saveError) return;
var result = createKeyBindings(item);
if (!result.valid) saveError = result.message;
});
if (saveError) {
status.textContent = saveError;
return;
}
var settings = {};
settings.rememberSpeed = document.getElementById("rememberSpeed").checked;
settings.forceLastSavedSpeed =
document.getElementById("forceLastSavedSpeed").checked;
settings.audioBoolean = document.getElementById("audioBoolean").checked;
settings.enabled = document.getElementById("enabled").checked;
settings.startHidden = document.getElementById("startHidden").checked;
settings.hideWithControls = document.getElementById("hideWithControls").checked;
settings.hideWithControlsTimer =
Math.min(15, Math.max(0.1, parseFloat(document.getElementById("hideWithControlsTimer").value) || tcDefaults.hideWithControlsTimer));
// Sync back to the legacy key if it exists, for backward compatibility
settings.hideWithYouTubeControls = settings.hideWithControls;
if (settings.hideWithControlsTimer < 0.1) settings.hideWithControlsTimer = 0.1;
if (settings.hideWithControlsTimer > 15) settings.hideWithControlsTimer = 15;
settings.controllerLocation = normalizeControllerLocation(
document.getElementById("controllerLocation").value
);
var s = {}; // Object to hold all settings to be saved
s.rememberSpeed = document.getElementById("rememberSpeed").checked;
s.forceLastSavedSpeed = document.getElementById(
"forceLastSavedSpeed"
).checked;
s.audioBoolean = document.getElementById("audioBoolean").checked;
s.enabled = document.getElementById("enabled").checked;
s.startHidden = document.getElementById("startHidden").checked;
s.controllerOpacity = document.getElementById("controllerOpacity").value;
s.blacklist = document
.getElementById("blacklist")
.value.replace(regStrip, "");
s.keyBindings = keyBindings; // Use the populated global keyBindings
// ADDED: Save nudge settings
s.enableSubtitleNudge = document.getElementById(
"enableSubtitleNudge"
).checked;
s.subtitleNudgeInterval =
settings.controllerOpacity =
parseFloat(document.getElementById("controllerOpacity").value) ||
tcDefaults.controllerOpacity;
settings.keyBindings = keyBindings;
settings.enableSubtitleNudge =
document.getElementById("enableSubtitleNudge").checked;
settings.subtitleNudgeInterval =
parseInt(document.getElementById("subtitleNudgeInterval").value, 10) ||
tcDefaults.subtitleNudgeInterval;
s.subtitleNudgeAmount =
parseFloat(document.getElementById("subtitleNudgeAmount").value) ||
tcDefaults.subtitleNudgeAmount;
// Basic validation for nudge interval and amount
if (s.subtitleNudgeInterval < 10) s.subtitleNudgeInterval = 10; // Min 10ms
if (s.subtitleNudgeAmount <= 0 || s.subtitleNudgeAmount > 0.1)
s.subtitleNudgeAmount = tcDefaults.subtitleNudgeAmount;
settings.subtitleNudgeAmount = tcDefaults.subtitleNudgeAmount;
// Remove old flat settings (original logic)
chrome.storage.sync.remove([
"resetSpeed",
"speedStep",
"fastSpeed",
"rewindTime",
"advanceTime",
"resetKeyCode",
"slowerKeyCode",
"fasterKeyCode",
"rewindKeyCode",
"advanceKeyCode",
"fastKeyCode"
]);
if (settings.subtitleNudgeInterval < 10) {
settings.subtitleNudgeInterval = 10;
}
if (settings.subtitleNudgeInterval > 1000) {
settings.subtitleNudgeInterval = 1000;
}
chrome.storage.sync.set(s, function () {
var status = document.getElementById("status");
status.textContent = "Options saved";
setTimeout(function () {
status.textContent = "";
}, 1000);
settings.controllerButtons = getControlBarOrder();
settings.showPopupControlBar =
document.getElementById("showPopupControlBar").checked;
settings.popupMatchHoverControls =
document.getElementById("popupMatchHoverControls").checked;
settings.popupControllerButtons = getPopupControlBarOrder();
// Collect site rules
settings.siteRules = [];
document.querySelectorAll(".site-rule").forEach((ruleEl) => {
var pattern = ruleEl.querySelector(".site-pattern").value.trim();
if (pattern.length === 0) return;
var rule = { pattern: pattern };
// Handle Enable toggle
rule.enabled = ruleEl.querySelector(".site-enabled").checked;
// Handle other site settings
const siteSettings = [
{ key: "startHidden", type: "checkbox" },
{ key: "hideWithControls", type: "checkbox" },
{ key: "hideWithControlsTimer", type: "text" },
{ key: "controllerLocation", type: "select" },
{ key: "rememberSpeed", type: "checkbox" },
{ key: "forceLastSavedSpeed", type: "checkbox" },
{ key: "audioBoolean", type: "checkbox" },
{ key: "controllerOpacity", type: "text" },
{ key: "showPopupControlBar", type: "checkbox" },
{ key: "enableSubtitleNudge", type: "checkbox" },
{ key: "subtitleNudgeInterval", type: "text" }
];
siteSettings.forEach((s) => {
var input = ruleEl.querySelector(`.site-${s.key}`);
if (!input) return;
var siteValue;
if (s.type === "checkbox") {
siteValue = input.checked;
} else {
siteValue = input.value;
}
var globalInput = document.getElementById(s.key);
if (globalInput) {
var globalValue = s.type === "checkbox" ? globalInput.checked : globalInput.value;
if (String(siteValue) !== String(globalValue)) {
rule[s.key] = siteValue;
}
} else {
rule[s.key] = siteValue;
}
});
if (ruleEl.querySelector(".override-controlbar").checked) {
var activeZone = ruleEl.querySelector(".site-cb-active");
if (activeZone) {
rule.controllerButtons = readControlBarOrder(activeZone);
}
}
if (ruleEl.querySelector(".override-popup-controlbar").checked) {
var popupActiveZone = ruleEl.querySelector(".site-popup-cb-active");
if (popupActiveZone) {
rule.popupControllerButtons = readControlBarOrder(popupActiveZone);
}
}
if (ruleEl.querySelector(".override-shortcuts").checked) {
var shortcuts = [];
ruleEl.querySelectorAll(".site-shortcuts-container .customs").forEach((shortcutRow) => {
var action = shortcutRow.dataset.action;
var keyInput = shortcutRow.querySelector(".customKey");
var valueInput = shortcutRow.querySelector(".customValue");
var forceCheckbox = shortcutRow.querySelector(".customForce");
var binding = normalizeStoredBinding(keyInput.vscBinding);
if (binding) {
shortcuts.push({
action: action,
key: binding.key,
keyCode: binding.keyCode,
code: binding.code,
disabled: binding.disabled === true,
value: customActionsNoValues.includes(action)
? 0
: Number(valueInput.value),
force: forceCheckbox ? forceCheckbox.checked : false
});
}
});
if (shortcuts.length > 0) rule.shortcuts = shortcuts;
}
settings.siteRules.push(rule);
});
// Legacy keys to remove
const legacyKeys = [
"resetSpeed", "speedStep", "fastSpeed", "rewindTime", "advanceTime",
"resetKeyCode", "slowerKeyCode", "fasterKeyCode", "rewindKeyCode",
"advanceKeyCode", "fastKeyCode", "blacklist"
];
chrome.storage.sync.remove(legacyKeys, function () {
chrome.storage.sync.set(settings, function () {
status.textContent = "Options saved";
setTimeout(function () {
status.textContent = "";
}, 1000);
});
});
}
function ensureAllDefaultBindings(storage) {
tcDefaults.keyBindings.forEach((binding) => {
// Special case for "display" to support legacy displayKeyCode
if (binding.action === "display" && storage.displayKeyCode) {
ensureDefaultBinding(storage, "display", "V", storage.displayKeyCode, 0);
} else {
ensureDefaultBinding(
storage,
binding.action,
binding.key,
binding.keyCode,
binding.value
);
}
});
}
function migrateLegacyBlacklist(storage) {
if (!storage.blacklist || typeof storage.blacklist !== "string") {
return [];
}
var siteRules = [];
var lines = storage.blacklist.split("\n");
lines.forEach((line) => {
var pattern = line.replace(regStrip, "");
if (pattern.length === 0) return;
siteRules.push({
pattern: pattern,
disableExtension: true
});
});
return siteRules;
}
function addSiteRuleShortcut(container, action, binding, value, force) {
var div = document.createElement("div");
div.setAttribute("class", "shortcut-row customs");
div.dataset.action = action;
var actionLabel = document.createElement("div");
actionLabel.className = "shortcut-label";
var actionLabels = {
display: "Show/hide controller",
move: "Move controller",
slower: "Decrease speed",
faster: "Increase speed",
rewind: "Rewind",
advance: "Advance",
reset: "Reset speed",
fast: "Preferred speed",
muted: "Mute",
pause: "Pause",
mark: "Set marker",
jump: "Jump to marker",
toggleSubtitleNudge: "Toggle subtitle nudge"
};
var actionLabelText = actionLabels[action] || action;
if (action === "toggleSubtitleNudge") {
// Check if the site rule is for YouTube.
// We look up the pattern from the site rule element this container belongs to.
var ruleEl = container.closest(".site-rule");
var pattern = ruleEl ? ruleEl.querySelector(".site-pattern").value : "";
if (!pattern.toLowerCase().includes("youtube.com")) {
actionLabelText += " (only for YouTube embeds)";
}
}
actionLabel.textContent = actionLabelText;
var keyInput = document.createElement("input");
keyInput.className = "customKey";
keyInput.type = "text";
keyInput.placeholder = "press a key";
updateCustomShortcutInputText(keyInput, binding || createDisabledBinding());
var valueInput = document.createElement("input");
valueInput.className = "customValue";
valueInput.type = "text";
valueInput.placeholder = "value (0.10)";
valueInput.value = value || 0;
if (customActionsNoValues.includes(action)) {
valueInput.disabled = true;
}
var forceLabel = document.createElement("label");
forceLabel.className = "force-label";
forceLabel.title = "Prevent website from capturing this key";
var forceCheckbox = document.createElement("input");
forceCheckbox.type = "checkbox";
forceCheckbox.className = "customForce";
forceCheckbox.checked = force === true || force === "true";
var forceText = document.createElement("span");
forceText.textContent = "Block site from capturing keypress";
forceText.className = "force-text";
forceLabel.appendChild(forceCheckbox);
forceLabel.appendChild(forceText);
div.appendChild(actionLabel);
div.appendChild(keyInput);
div.appendChild(valueInput);
div.appendChild(forceLabel);
container.appendChild(div);
}
function createSiteRule(rule) {
var template = document.getElementById("siteRuleTemplate");
var clone = template.content.cloneNode(true);
var ruleEl = clone.querySelector(".site-rule");
var pattern = rule && rule.pattern ? rule.pattern : "";
ruleEl.querySelector(".site-pattern").value = pattern;
// Make the rule body collapsed by default
var ruleBody = ruleEl.querySelector(".site-rule-body");
ruleBody.style.display = "none";
ruleEl.classList.add("collapsed");
var enabledCheckbox = ruleEl.querySelector(".site-enabled");
var contentEl = ruleEl.querySelector(".site-rule-content");
function updateDisabledState() {
if (enabledCheckbox.checked) {
contentEl.classList.remove("disabled-rule");
} else {
contentEl.classList.add("disabled-rule");
}
}
enabledCheckbox.addEventListener("change", updateDisabledState);
if (rule) {
if (rule.enabled !== undefined) {
enabledCheckbox.checked = rule.enabled;
} else if (rule.disableExtension !== undefined) {
enabledCheckbox.checked = !rule.disableExtension;
} else {
enabledCheckbox.checked = true;
}
} else {
enabledCheckbox.checked = true;
}
updateDisabledState();
const settings = [
{ key: "startHidden", type: "checkbox" },
{ key: "hideWithControls", type: "checkbox" },
{ key: "hideWithControlsTimer", type: "text" },
{ key: "controllerLocation", type: "select" },
{ key: "rememberSpeed", type: "checkbox" },
{ key: "forceLastSavedSpeed", type: "checkbox" },
{ key: "audioBoolean", type: "checkbox" },
{ key: "controllerOpacity", type: "text" },
{ key: "showPopupControlBar", type: "checkbox" },
{ key: "enableSubtitleNudge", type: "checkbox" },
{ key: "subtitleNudgeInterval", type: "text" }
];
settings.forEach((s) => {
var input = ruleEl.querySelector(`.site-${s.key}`);
if (!input) return;
var value;
if (rule && rule[s.key] !== undefined) {
value = rule[s.key];
} else {
// Initialize with current global value
var globalInput = document.getElementById(s.key);
if (globalInput) {
if (s.type === "checkbox") {
value = globalInput.checked;
} else {
value = globalInput.value;
}
}
}
if (s.type === "checkbox") {
input.checked = value;
} else {
input.value = value;
}
});
if (rule && Array.isArray(rule.controllerButtons)) {
ruleEl.querySelector(".override-controlbar").checked = true;
var cbContainer = ruleEl.querySelector(".site-controlbar-container");
cbContainer.style.display = "block";
populateControlBarZones(
ruleEl.querySelector(".site-cb-active"),
ruleEl.querySelector(".site-cb-available"),
rule.controllerButtons
);
}
if (rule && Array.isArray(rule.popupControllerButtons)) {
ruleEl.querySelector(".override-popup-controlbar").checked = true;
var popupCbContainer = ruleEl.querySelector(".site-popup-controlbar-container");
popupCbContainer.style.display = "block";
populateControlBarZones(
ruleEl.querySelector(".site-popup-cb-active"),
ruleEl.querySelector(".site-popup-cb-available"),
rule.popupControllerButtons
);
}
if (rule && Array.isArray(rule.shortcuts) && rule.shortcuts.length > 0) {
ruleEl.querySelector(".override-shortcuts").checked = true;
var container = ruleEl.querySelector(".site-shortcuts-container");
container.style.display = "block";
rule.shortcuts.forEach((shortcut) => {
addSiteRuleShortcut(
container,
shortcut.action,
shortcut,
shortcut.value,
shortcut.force
);
});
}
document.getElementById("siteRulesContainer").appendChild(ruleEl);
}
function populateDefaultSiteShortcuts(container) {
tcDefaults.keyBindings.forEach((binding) => {
addSiteRuleShortcut(container, binding.action, binding, binding.value, false);
});
}
function createControlBarBlock(buttonId) {
var def = controllerButtonDefs[buttonId];
if (!def) return null;
var block = document.createElement("div");
block.className = "cb-block";
block.dataset.buttonId = buttonId;
block.draggable = true;
var grip = document.createElement("span");
grip.className = "cb-grip";
var icon = document.createElement("span");
icon.className = "cb-icon";
icon.textContent = def.icon;
var label = document.createElement("span");
label.className = "cb-label";
label.textContent = def.name;
block.appendChild(grip);
block.appendChild(icon);
block.appendChild(label);
return block;
}
function populateControlBarZones(activeZone, availableZone, activeIds) {
activeZone.innerHTML = "";
availableZone.innerHTML = "";
activeIds.forEach(function (id) {
var block = createControlBarBlock(id);
if (block) activeZone.appendChild(block);
});
Object.keys(controllerButtonDefs).forEach(function (id) {
if (!activeIds.includes(id)) {
var block = createControlBarBlock(id);
if (block) availableZone.appendChild(block);
}
});
}
function readControlBarOrder(activeZone) {
var blocks = activeZone.querySelectorAll(".cb-block");
return Array.from(blocks).map(function (block) {
return block.dataset.buttonId;
});
}
function populateControlBarEditor(activeIds) {
populateControlBarZones(
document.getElementById("controlBarActive"),
document.getElementById("controlBarAvailable"),
activeIds
);
}
function getControlBarOrder() {
return readControlBarOrder(document.getElementById("controlBarActive"));
}
function populatePopupControlBarEditor(activeIds) {
populateControlBarZones(
document.getElementById("popupControlBarActive"),
document.getElementById("popupControlBarAvailable"),
activeIds
);
}
function getPopupControlBarOrder() {
return readControlBarOrder(document.getElementById("popupControlBarActive"));
}
function updatePopupEditorDisabledState() {
var checkbox = document.getElementById("popupMatchHoverControls");
var wrap = document.getElementById("popupCbEditorWrap");
if (!checkbox || !wrap) return;
if (checkbox.checked) {
wrap.classList.add("cb-editor-disabled");
} else {
wrap.classList.remove("cb-editor-disabled");
}
}
function getDragAfterElement(container, x, y) {
var elements = Array.from(
container.querySelectorAll(".cb-block:not(.cb-dragging)")
);
for (var i = 0; i < elements.length; i++) {
var box = elements[i].getBoundingClientRect();
var centerX = box.left + box.width / 2;
var centerY = box.top + box.height / 2;
var rowThresh = box.height * 0.5;
if (y - centerY > rowThresh) continue;
if (centerY - y > rowThresh) return elements[i];
if (x < centerX) return elements[i];
}
return undefined;
}
function initControlBarEditor() {
var draggedBlock = null;
function clearControlBarDropTargets(activeZone) {
document.querySelectorAll(".cb-dropzone.cb-over").forEach(function (zone) {
if (zone !== activeZone) {
zone.classList.remove("cb-over");
}
});
}
document.addEventListener("dragstart", function (e) {
var block = e.target.closest(".cb-block");
if (!block) return;
draggedBlock = block;
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("text/plain", block.dataset.buttonId);
requestAnimationFrame(function () {
block.classList.add("cb-dragging");
});
});
document.addEventListener("dragend", function (e) {
var block = e.target.closest(".cb-block");
if (!block) return;
block.classList.remove("cb-dragging");
draggedBlock = null;
clearControlBarDropTargets(null);
});
document.addEventListener("dragover", function (e) {
var zone = e.target.closest(".cb-dropzone");
if (!zone) {
clearControlBarDropTargets(null);
return;
}
e.preventDefault();
if (e.dataTransfer) {
e.dataTransfer.dropEffect = "move";
}
clearControlBarDropTargets(zone);
zone.classList.add("cb-over");
if (!draggedBlock) return;
var afterEl = getDragAfterElement(zone, e.clientX, e.clientY);
if (afterEl) {
zone.insertBefore(draggedBlock, afterEl);
} else {
zone.appendChild(draggedBlock);
}
});
document.addEventListener("drop", function (e) {
var zone = e.target.closest(".cb-dropzone");
if (zone) {
e.preventDefault();
}
clearControlBarDropTargets(null);
});
}
// MODIFIED: restore_options to include nudge settings
function restore_options() {
chrome.storage.sync.get(tcDefaults, function (storage) {
document.getElementById("rememberSpeed").checked = storage.rememberSpeed;
@@ -245,90 +1156,105 @@ function restore_options() {
document.getElementById("audioBoolean").checked = storage.audioBoolean;
document.getElementById("enabled").checked = storage.enabled;
document.getElementById("startHidden").checked = storage.startHidden;
// Migration/Normalization for hideWithControls
const hideWithControls = typeof storage.hideWithControls !== "undefined"
? storage.hideWithControls
: storage.hideWithYouTubeControls;
document.getElementById("hideWithControls").checked = hideWithControls;
document.getElementById("hideWithControlsTimer").value =
storage.hideWithControlsTimer || tcDefaults.hideWithControlsTimer;
document.getElementById("controllerLocation").value =
normalizeControllerLocation(storage.controllerLocation);
document.getElementById("controllerOpacity").value =
storage.controllerOpacity;
document.getElementById("blacklist").value = storage.blacklist;
// ADDED: Restore nudge settings
document.getElementById("showPopupControlBar").checked =
storage.showPopupControlBar !== false;
document.getElementById("enableSubtitleNudge").checked =
storage.enableSubtitleNudge;
document.getElementById("subtitleNudgeInterval").value =
storage.subtitleNudgeInterval;
document.getElementById("subtitleNudgeAmount").value =
storage.subtitleNudgeAmount;
// Original key binding restoration logic
if (
!Array.isArray(storage.keyBindings) ||
storage.keyBindings.length === 0
) {
// If keyBindings missing or not an array, use defaults from tcDefaults
storage.keyBindings = tcDefaults.keyBindings;
if (!Array.isArray(storage.keyBindings) || storage.keyBindings.length === 0) {
storage.keyBindings = tcDefaults.keyBindings.slice();
}
if (storage.keyBindings.filter((x) => x.action == "display").length == 0) {
storage.keyBindings.push({
action: "display",
value: 0,
force: false,
predefined: true,
key: storage.displayKeyCode || tcDefaults.displayKeyCode
ensureAllDefaultBindings(storage);
document.querySelectorAll(".customs:not([id])").forEach((row) => row.remove());
storage.keyBindings.forEach((item) => {
var row = document.getElementById(item.action);
var normalizedBinding = normalizeStoredBinding(item);
if (!row) {
add_shortcut(item.action, item.value);
row = document.querySelector(".shortcut-row.customs:last-of-type");
}
if (!row) return;
var keyInput = row.querySelector(".customKey");
if (keyInput) {
updateCustomShortcutInputText(keyInput, normalizedBinding || null);
}
var valueInput = row.querySelector(".customValue");
if (customActionsNoValues.includes(item.action)) {
if (valueInput) {
valueInput.value = "N/A";
valueInput.disabled = true;
}
} else if (valueInput) {
valueInput.value = item.value;
}
});
refreshAddShortcutSelector();
// Load site rules (use defaults if none in storage or if storage has empty array)
var siteRules = Array.isArray(storage.siteRules) && storage.siteRules.length > 0
? storage.siteRules
: (storage.blacklist ? migrateLegacyBlacklist(storage) : (tcDefaults.siteRules || []));
// If we migrated from blacklist, save the new format
if (storage.blacklist && siteRules.length > 0) {
chrome.storage.sync.set({ siteRules: siteRules });
chrome.storage.sync.remove(["blacklist"]);
}
document.getElementById("siteRulesContainer").innerHTML = "";
if (siteRules.length > 0) {
siteRules.forEach((rule) => {
if (rule && rule.pattern) {
createSiteRule(rule);
}
});
}
// Clear existing dynamic shortcuts before restoring (if any were added by mistake)
const dynamicShortcuts = document.querySelectorAll(".customs:not([id])");
dynamicShortcuts.forEach((sc) => sc.remove());
var controllerButtons = Array.isArray(storage.controllerButtons)
? storage.controllerButtons
: tcDefaults.controllerButtons;
populateControlBarEditor(controllerButtons);
for (let i in storage.keyBindings) {
var item = storage.keyBindings[i];
if (item.predefined) {
if (item["action"] == "display" && typeof item["key"] === "undefined") {
item["key"] = storage.displayKeyCode || tcDefaults.displayKeyCode;
}
if (customActionsNoValues.includes(item["action"])) {
const el = document.querySelector(
"#" + item["action"] + " .customValue"
);
if (el) el.disabled = true;
}
const keyEl = document.querySelector(
"#" + item["action"] + " .customKey"
);
const valEl = document.querySelector(
"#" + item["action"] + " .customValue"
);
const forceEl = document.querySelector(
"#" + item["action"] + " .customForce"
);
if (keyEl) updateCustomShortcutInputText(keyEl, item["key"]);
if (valEl) valEl.value = item["value"];
if (forceEl) forceEl.value = String(item["force"]); // Ensure string for select value
} else {
// Non-predefined, dynamically added shortcuts
add_shortcut();
const dom = document.querySelector(".customs:last-of-type"); // Gets the newly added one
dom.querySelector(".customDo").value = item["action"];
if (customActionsNoValues.includes(item["action"])) {
dom.querySelector(".customValue").disabled = true;
}
updateCustomShortcutInputText(
dom.querySelector(".customKey"),
item["key"]
);
dom.querySelector(".customValue").value = item["value"];
dom.querySelector(".customForce").value = String(item["force"]);
}
}
document.getElementById("popupMatchHoverControls").checked =
storage.popupMatchHoverControls !== false;
var popupButtons = Array.isArray(storage.popupControllerButtons)
? storage.popupControllerButtons
: tcDefaults.popupControllerButtons;
populatePopupControlBarEditor(popupButtons);
updatePopupEditorDisabledState();
});
}
function restore_defaults() {
/* ... same as your original, tcDefaults now includes nudge defaults ... */
// Remove all dynamically added shortcuts first
document.querySelectorAll(".customs:not([id])").forEach((el) => el.remove());
// Then set defaults and restore options, which will re-add predefined ones correctly
chrome.storage.sync.set(tcDefaults, function () {
restore_options(); // This will populate based on tcDefaults
restore_options();
var status = document.getElementById("status");
status.textContent = "Default options restored";
setTimeout(function () {
@@ -337,30 +1263,46 @@ function restore_defaults() {
});
}
function show_experimental() {
/* ... same as your original ... */
document
.querySelectorAll(".customForce")
.forEach((item) => (item.style.display = "inline-block"));
}
document.addEventListener("DOMContentLoaded", function () {
/* ... same as your original event listeners setup ... */
var manifest = chrome.runtime.getManifest();
var versionElement = document.getElementById("app-version");
if (versionElement) {
versionElement.textContent = manifest.version;
}
restore_options();
initControlBarEditor();
document.getElementById("popupMatchHoverControls")
.addEventListener("change", updatePopupEditorDisabledState);
document.getElementById("save").addEventListener("click", save_options);
document.getElementById("add").addEventListener("click", add_shortcut);
const addSelector = document.getElementById("addShortcutSelector");
if (addSelector) {
addSelector.addEventListener("change", function (e) {
if (e.target.value) {
add_shortcut(e.target.value);
e.target.value = ""; // Reset selector
}
});
}
document
.getElementById("restore")
.addEventListener("click", restore_defaults);
document
.getElementById("experimental")
.addEventListener("click", show_experimental);
.getElementById("addSiteRule")
.addEventListener("click", function () {
createSiteRule(null);
});
function eventCaller(event, className, funcName) {
if (!event.target.classList || !event.target.classList.contains(className))
if (!event.target.classList || !event.target.classList.contains(className)) {
return;
}
funcName(event);
}
document.addEventListener("keypress", (event) =>
eventCaller(event, "customValue", inputFilterNumbersOnly)
);
@@ -373,19 +1315,107 @@ document.addEventListener("DOMContentLoaded", function () {
document.addEventListener("keydown", (event) =>
eventCaller(event, "customKey", recordKeyPress)
);
document.addEventListener("click", (event) =>
eventCaller(event, "removeParent", function () {
document.addEventListener("click", (event) => {
if (event.target.classList.contains("removeParent")) {
event.target.parentNode.remove();
})
);
document.addEventListener("change", (event) => {
eventCaller(event, "customDo", function () {
if (customActionsNoValues.includes(event.target.value)) {
event.target.nextElementSibling.nextElementSibling.disabled = true;
event.target.nextElementSibling.nextElementSibling.value = 0; // Or "" if placeholder is preferred
refreshAddShortcutSelector();
return;
}
if (event.target.classList.contains("remove-site-rule")) {
event.target.closest(".site-rule").remove();
return;
}
if (event.target.classList.contains("toggle-site-rule")) {
var ruleEl = event.target.closest(".site-rule");
var ruleBody = ruleEl.querySelector(".site-rule-body");
var isCollapsed = ruleEl.classList.contains("collapsed");
if (isCollapsed) {
ruleBody.style.display = "block";
ruleEl.classList.remove("collapsed");
event.target.textContent = "\u2212";
} else {
event.target.nextElementSibling.nextElementSibling.disabled = false;
ruleBody.style.display = "none";
ruleEl.classList.add("collapsed");
event.target.textContent = "\u002b";
}
});
return;
}
});
document.addEventListener("change", (event) => {
if (event.target.classList.contains("customDo")) {
var valueInput = event.target.nextElementSibling.nextElementSibling;
if (customActionsNoValues.includes(event.target.value)) {
valueInput.disabled = true;
valueInput.value = 0;
} else {
valueInput.disabled = false;
}
}
// Handle site rule override checkboxes
if (event.target.classList.contains("override-shortcuts")) {
var container = event.target
.closest(".site-rule-shortcuts")
.querySelector(".site-shortcuts-container");
if (event.target.checked) {
container.style.display = "block";
if (container.children.length === 0) {
populateDefaultSiteShortcuts(container);
}
} else {
container.style.display = "none";
}
}
if (event.target.classList.contains("override-controlbar")) {
var cbContainer = event.target
.closest(".site-rule-controlbar")
.querySelector(".site-controlbar-container");
if (event.target.checked) {
cbContainer.style.display = "block";
var activeZone = cbContainer.querySelector(".site-cb-active");
var availableZone = cbContainer.querySelector(".site-cb-available");
if (
activeZone &&
availableZone &&
activeZone.children.length === 0 &&
availableZone.children.length === 0
) {
populateControlBarZones(
activeZone,
availableZone,
getControlBarOrder()
);
}
} else {
cbContainer.style.display = "none";
}
}
if (event.target.classList.contains("override-popup-controlbar")) {
var popupCbContainer = event.target
.closest(".site-rule-controlbar")
.querySelector(".site-popup-controlbar-container");
if (event.target.checked) {
popupCbContainer.style.display = "block";
var popupActiveZone = popupCbContainer.querySelector(".site-popup-cb-active");
var popupAvailableZone = popupCbContainer.querySelector(".site-popup-cb-available");
if (
popupActiveZone &&
popupAvailableZone &&
popupActiveZone.children.length === 0 &&
popupAvailableZone.children.length === 0
) {
populateControlBarZones(
popupActiveZone,
popupAvailableZone,
getPopupControlBarOrder()
);
}
} else {
popupCbContainer.style.display = "none";
}
}
});
});
+238 -19
View File
@@ -1,34 +1,253 @@
body {
min-width: 8em;
:root {
--bg: #f4f5f7;
--panel: #ffffff;
--border: #e2e5e9;
--border-strong: #d4d9e0;
--text: #17191c;
--muted: #626b76;
--accent: #111827;
}
hr {
width: 100%;
border: 0;
height: 0;
border-top: 1px solid rgba(0, 0, 0, 0.3);
margin: 0.6em 0;
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
min-width: 220px;
background: var(--bg);
color: var(--text);
font: 13px/1.45 "Avenir Next", "SF Pro Text", "Segoe UI", sans-serif;
padding: 12px;
}
.popup-shell {
display: flex;
flex-direction: column;
gap: 10px;
}
.popup-header {
display: flex;
align-items: center;
justify-content: space-between;
padding-bottom: 8px;
border-bottom: 1px solid var(--border);
}
.popup-title {
font-weight: 600;
font-size: 15px;
font-family: "Avenir Next", "SF Pro Display", "Segoe UI", sans-serif;
letter-spacing: -0.01em;
}
.popup-version {
font-size: 11px;
font-weight: 600;
color: var(--muted);
padding: 2px 7px;
border: 1px solid var(--border);
border-radius: 999px;
background: var(--panel);
}
.popup-actions {
display: flex;
flex-direction: column;
gap: 6px;
}
button {
appearance: none;
width: 100%;
background-image: linear-gradient(#ededed, #ededed 38%, #dedede);
border: 1px solid rgba(0, 0, 0, 0.25);
border-radius: 2px;
outline: none;
box-shadow: 0 1px 0 rgba(0, 0, 0, 0.08),
inset 0 1px 2px rgba(255, 255, 255, 0.75);
color: #444;
text-shadow: 0 1px 0 rgb(240, 240, 240);
min-height: 32px;
padding: 0 12px;
border: 1px solid var(--border-strong);
border-radius: 8px;
background: var(--panel);
color: var(--text);
font: inherit;
font-weight: 500;
cursor: pointer;
transition: background 120ms ease, border-color 120ms ease;
}
button:hover {
background: #f8f9fb;
border-color: #c5ccd5;
}
button:active {
background: #f1f3f5;
}
button:focus-visible {
outline: 2px solid rgba(17, 24, 39, 0.14);
outline-offset: 2px;
}
#refresh {
background: var(--accent);
border-color: var(--accent);
color: #fff;
}
#refresh:hover {
background: #1f2937;
border-color: #1f2937;
}
.popup-divider {
height: 1px;
background: var(--border);
margin: 2px 0;
}
.popup-control-bar {
display: flex;
align-items: center;
justify-content: center;
gap: 4px;
padding: 6px 10px;
background: var(--panel);
border: 1px solid var(--border-strong);
border-radius: 8px;
}
.popup-speed {
font-family: "Lucida Console", Monaco, monospace;
font-size: 13px;
font-weight: bold;
color: var(--text);
margin-right: 4px;
line-height: 1;
user-select: none;
white-space: nowrap;
}
.popup-control-bar button {
width: auto;
min-height: 24px;
border: 1px solid var(--border-strong);
border-radius: 6px;
background: var(--bg);
color: var(--text);
font-family: "Lucida Console", Monaco, monospace;
font-size: 13px;
line-height: 13px;
font-weight: bold;
padding: 3px 7px;
cursor: pointer;
}
.popup-control-bar button:hover {
background: var(--panel);
border-color: var(--border-strong);
}
.popup-control-bar button:active {
background: var(--bg);
}
.popup-control-bar button.rw {
opacity: 0.55;
}
.popup-control-bar button.hideButton {
opacity: 0.55;
}
.popup-status {
font-size: 12px;
color: var(--muted);
font-weight: 500;
text-align: center;
padding: 2px 0;
}
.popup-links {
display: flex;
flex-direction: column;
gap: 6px;
padding-top: 8px;
border-top: 1px solid var(--border);
}
.popup-secondary {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
}
.secondary {
font-size: 0.95em;
margin: 0.15em 0;
font-size: 12px;
min-height: 28px;
color: var(--muted);
}
.donate-wrap {
display: grid;
grid-template-columns: 1fr;
}
.donate-split {
display: grid;
grid-template-columns: 1fr 1fr;
}
.donate-split button {
width: auto;
border-radius: 0;
min-height: 28px;
}
.donate-split button:first-child {
border-radius: 8px 0 0 8px;
border-right: 0;
}
.donate-split button:last-child {
border-radius: 0 8px 8px 0;
}
.hide {
display: none;
display: none !important;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #111315;
--panel: #171a1d;
--border: #2b3138;
--border-strong: #3a414a;
--text: #f2f4f6;
--muted: #a0a8b2;
--accent: #f2f4f6;
}
body {
color-scheme: dark;
}
button:hover {
background: #1f2226;
border-color: #4a515a;
}
button:active {
background: #252a2f;
}
#refresh {
background: #f2f4f6;
border-color: #f2f4f6;
color: #111315;
}
#refresh:hover {
background: #dfe3e8;
border-color: #dfe3e8;
}
}
+34 -10
View File
@@ -1,18 +1,42 @@
<!DOCTYPE html>
<!doctype html>
<html>
<head>
<title>Video Speed Controller: Popup</title>
<meta charset="utf-8" />
<title>Speeder</title>
<link rel="stylesheet" href="popup.css" />
<script src="popup.js"></script>
</head>
<body>
<button id="enable" class="hide">Enable</button>
<button id="disable">Disable</button>
<span id="status" class="hide"></span>
<hr />
<button id="config">Settings</button>
<hr />
<button id="feedback" class="secondary">Send feedback</button>
<button id="about" class="secondary">About</button>
<div class="popup-shell">
<div class="popup-header">
<span class="popup-title">Speeder</span>
<span class="popup-version">v<span id="app-version"></span></span>
</div>
<div class="popup-actions">
<button id="refresh">Rescan page for videos</button>
<div class="popup-divider"></div>
<div id="popupControlBar" class="popup-control-bar">
<span id="popupSpeed" class="popup-speed">1.00</span>
</div>
<div class="popup-divider"></div>
<button id="enable" class="hide">Enable</button>
<button id="disable">Disable</button>
</div>
<div id="status" class="popup-status hide"></div>
<div class="popup-links">
<button id="config">Settings</button>
<div class="popup-secondary">
<button id="feedback" class="secondary">Feedback</button>
<button id="about" class="secondary">About</button>
</div>
<div id="donateWrap" class="donate-wrap">
<button id="donate" class="secondary">Donate</button>
<div id="donateOptions" class="donate-split hide">
<button id="donateKofi" class="secondary">Ko-fi</button>
<button id="donateGithub" class="secondary">Sponsors</button>
</div>
</div>
</div>
</div>
</body>
</html>
+338 -16
View File
@@ -1,14 +1,250 @@
document.addEventListener("DOMContentLoaded", function () {
var regStrip = /^[\r\t\f\v ]+|[\r\t\f\v ]+$/gm;
var controllerButtonDefs = {
rewind: { label: "\u00AB", className: "rw" },
slower: { label: "\u2212", className: "" },
faster: { label: "+", className: "" },
advance: { label: "\u00BB", className: "rw" },
display: { label: "\u00D7", className: "hideButton" },
reset: { label: "\u21BA", className: "" },
fast: { label: "\u2605", className: "" },
settings: { label: "\u2699", className: "" },
pause: { label: "\u23EF", className: "" },
muted: { label: "M", className: "" },
mark: { label: "\u2691", className: "" },
jump: { label: "\u21E5", className: "" }
};
var defaultButtons = ["rewind", "slower", "faster", "advance", "display"];
var storageDefaults = {
enabled: true,
showPopupControlBar: true,
controllerButtons: defaultButtons,
popupMatchHoverControls: true,
popupControllerButtons: defaultButtons,
siteRules: [],
blacklist: `\
www.instagram.com
twitter.com
vine.co
imgur.com
teams.microsoft.com
`.replace(/^[\r\t\f\v ]+|[\r\t\f\v ]+$/gm, "")
};
var renderToken = 0;
function escapeStringRegExp(str) {
const m = /[|\\{}()[\]^$+*?.]/g;
return str.replace(m, "\\$&");
}
function isBlacklisted(url, blacklist) {
let b = false;
const l = blacklist ? blacklist.split("\n") : [];
l.forEach((m) => {
if (b) return;
m = m.replace(regStrip, "");
if (m.length == 0) return;
let r;
if (m.startsWith("/") && m.lastIndexOf("/") > 0) {
try {
const ls = m.lastIndexOf("/");
r = new RegExp(m.substring(1, ls), m.substring(ls + 1));
} catch (e) {
return;
}
} else r = new RegExp(escapeStringRegExp(m));
if (r && r.test(url)) b = true;
});
return b;
}
function matchSiteRule(url, siteRules) {
if (!url || !Array.isArray(siteRules)) return null;
for (var i = 0; i < siteRules.length; i++) {
var rule = siteRules[i];
if (!rule || !rule.pattern) continue;
var pattern = rule.pattern.replace(regStrip, "");
if (pattern.length === 0) continue;
var re;
if (pattern.startsWith("/") && pattern.lastIndexOf("/") > 0) {
try {
var ls = pattern.lastIndexOf("/");
re = new RegExp(pattern.substring(1, ls), pattern.substring(ls + 1));
} catch (e) {
continue;
}
} else {
re = new RegExp(escapeStringRegExp(pattern));
}
if (re && re.test(url)) return rule;
}
return null;
}
function isSiteRuleDisabled(rule) {
return Boolean(
rule &&
(rule.enabled === false || rule.disableExtension === true)
);
}
function resolvePopupButtons(storage, siteRule) {
if (siteRule && Array.isArray(siteRule.popupControllerButtons)) {
return siteRule.popupControllerButtons;
}
if (storage.popupMatchHoverControls) {
if (siteRule && Array.isArray(siteRule.controllerButtons)) {
return siteRule.controllerButtons;
}
if (Array.isArray(storage.controllerButtons)) {
return storage.controllerButtons;
}
}
if (Array.isArray(storage.popupControllerButtons)) {
return storage.popupControllerButtons;
}
return defaultButtons;
}
function setControlBarVisible(visible) {
var bar = document.getElementById("popupControlBar");
var dividers = document.querySelectorAll(".popup-divider");
if (bar) bar.style.display = visible ? "" : "none";
dividers.forEach(function (d) { d.style.display = visible ? "" : "none"; });
}
function sendToActiveTab(message, callback) {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
if (tabs[0] && tabs[0].id) {
chrome.tabs.sendMessage(tabs[0].id, message, function (response) {
if (chrome.runtime.lastError) {
if (callback) callback(null);
} else {
if (callback) callback(response);
}
});
} else {
if (callback) callback(null);
}
});
}
function getActiveTabContext(callback) {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
var activeTab = tabs && tabs[0] ? tabs[0] : null;
if (!activeTab || !activeTab.id) {
if (callback) callback({ tab: null, url: "" });
return;
}
var tabUrl = typeof activeTab.url === "string" ? activeTab.url : "";
if (tabUrl.length > 0) {
if (callback) callback({ tab: activeTab, url: tabUrl });
return;
}
chrome.tabs.sendMessage(
activeTab.id,
{ action: "get_page_context" },
function (response) {
if (chrome.runtime.lastError) {
if (callback) callback({ tab: activeTab, url: "" });
return;
}
var pageUrl =
response && typeof response.url === "string" ? response.url : "";
if (callback) callback({ tab: activeTab, url: pageUrl });
}
);
});
}
function updateSpeedDisplay(speed) {
var el = document.getElementById("popupSpeed");
if (el) el.textContent = (speed != null ? Number(speed) : 1).toFixed(2);
}
function querySpeed() {
sendToActiveTab({ action: "get_speed" }, function (response) {
if (response && response.speed != null) {
updateSpeedDisplay(response.speed);
}
});
}
function buildControlBar(buttons) {
var bar = document.getElementById("popupControlBar");
if (!bar) return;
var existing = bar.querySelectorAll("button");
existing.forEach(function (btn) { btn.remove(); });
buttons.forEach(function (btnId) {
if (btnId === "nudge") return;
var def = controllerButtonDefs[btnId];
if (!def) return;
var btn = document.createElement("button");
btn.dataset.action = btnId;
btn.textContent = def.label;
if (def.className) btn.className = def.className;
btn.title = btnId.charAt(0).toUpperCase() + btnId.slice(1);
btn.addEventListener("click", function () {
if (btnId === "settings") {
window.open(chrome.runtime.getURL("options.html"));
return;
}
sendToActiveTab(
{ action: "run_action", actionName: btnId },
function (response) {
if (response && response.speed != null) {
updateSpeedDisplay(response.speed);
}
}
);
});
bar.appendChild(btn);
});
}
var manifest = chrome.runtime.getManifest();
var versionElement = document.querySelector("#app-version");
if (versionElement) {
versionElement.innerText = manifest.version;
}
document.querySelector("#config").addEventListener("click", function () {
window.open(chrome.runtime.getURL("options.html"));
});
document.querySelector("#about").addEventListener("click", function () {
window.open("https://github.com/codebicycle/videospeed");
window.open("https://github.com/SoPat712/Speeder");
});
document.querySelector("#feedback").addEventListener("click", function () {
window.open("https://github.com/codebicycle/videospeed/issues");
window.open("https://github.com/SoPat712/Speeder/issues");
});
document.querySelector("#donate").addEventListener("click", function () {
this.classList.add("hide");
document.querySelector("#donateOptions").classList.remove("hide");
});
document.querySelector("#donateKofi").addEventListener("click", function () {
window.open("https://ko-fi.com/joshpatra");
});
document.querySelector("#donateGithub").addEventListener("click", function () {
window.open("https://github.com/sponsors/SoPat712");
});
document.querySelector("#enable").addEventListener("click", function () {
@@ -19,20 +255,100 @@ document.addEventListener("DOMContentLoaded", function () {
toggleEnabled(false, settingsSavedReloadMessage);
});
chrome.storage.sync.get({ enabled: true }, function (storage) {
toggleEnabledUI(storage.enabled);
document.querySelector("#refresh").addEventListener("click", function () {
setStatusMessage("Rescanning page...");
sendToActiveTab({ action: "rescan_page" }, function (response) {
if (!response) {
setStatusMessage("Cannot run on this page.");
} else if (response.status === "complete") {
setStatusMessage("Scan complete. Closing...");
setTimeout(function () { window.close(); }, 500);
} else {
setStatusMessage("Scan failed. Please reload the page.");
}
});
});
function renderForActiveTab() {
var currentRenderToken = ++renderToken;
chrome.storage.sync.get(storageDefaults, function (storage) {
if (currentRenderToken !== renderToken) return;
getActiveTabContext(function (context) {
if (currentRenderToken !== renderToken) return;
var url = context && context.url ? context.url : "";
var siteRule = matchSiteRule(url, storage.siteRules);
var blacklisted = isBlacklisted(url, storage.blacklist);
var siteDisabled = isSiteRuleDisabled(siteRule);
var siteAvailable =
storage.enabled !== false && !blacklisted && !siteDisabled;
var showBar = storage.showPopupControlBar !== false;
if (siteRule && siteRule.showPopupControlBar !== undefined) {
showBar = siteRule.showPopupControlBar;
}
toggleEnabledUI(storage.enabled !== false);
buildControlBar(resolvePopupButtons(storage, siteRule));
setControlBarVisible(siteAvailable && showBar);
if (blacklisted) {
setStatusMessage("Site is blacklisted.");
updateSpeedDisplay(1);
return;
}
if (siteDisabled) {
setStatusMessage("Speeder is disabled for this site.");
updateSpeedDisplay(1);
return;
}
clearStatusMessage();
if (siteAvailable) {
querySpeed();
} else {
updateSpeedDisplay(1);
}
});
});
}
chrome.tabs.onActivated.addListener(function () {
renderForActiveTab();
});
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (!tab || tab.active !== true) return;
if (changeInfo.url !== undefined || changeInfo.status === "complete") {
renderForActiveTab();
}
});
chrome.storage.onChanged.addListener(function (changes, areaName) {
if (areaName !== "sync") return;
if (
changes.enabled ||
changes.showPopupControlBar ||
changes.controllerButtons ||
changes.popupMatchHoverControls ||
changes.popupControllerButtons ||
changes.siteRules ||
changes.blacklist
) {
renderForActiveTab();
}
});
renderForActiveTab();
function toggleEnabled(enabled, callback) {
chrome.storage.sync.set(
{
enabled: enabled
},
function () {
toggleEnabledUI(enabled);
if (callback) callback(enabled);
}
);
chrome.storage.sync.set({ enabled: enabled }, function () {
toggleEnabledUI(enabled);
if (callback) callback(enabled);
});
}
function toggleEnabledUI(enabled) {
@@ -42,9 +358,9 @@ document.addEventListener("DOMContentLoaded", function () {
const suffix = `${enabled ? "" : "_disabled"}.png`;
chrome.browserAction.setIcon({
path: {
"19": "icons/icon19" + suffix,
"38": "icons/icon38" + suffix,
"48": "icons/icon48" + suffix
19: "icons/icon19" + suffix,
38: "icons/icon38" + suffix,
48: "icons/icon48" + suffix
}
});
}
@@ -60,4 +376,10 @@ document.addEventListener("DOMContentLoaded", function () {
status_element.classList.toggle("hide", false);
status_element.innerText = str;
}
function clearStatusMessage() {
const status_element = document.querySelector("#status");
status_element.classList.toggle("hide", true);
status_element.innerText = "";
}
});
+102 -2
View File
@@ -4,6 +4,8 @@
font-size: 13px;
}
#controller:hover #controls,
#controller:focus-within #controls,
:host(:hover) #controls {
display: inline;
}
@@ -12,16 +14,21 @@
position: absolute;
top: 0;
left: 0;
transform: translate(0, 0);
pointer-events: auto;
background: black;
color: white;
border-radius: 5px;
padding: 5px;
margin: 10px 10px 10px 15px;
margin: 0;
cursor: default;
z-index: 9999999;
/* Stay above the local video surface without overtaking page-level dialogs. */
z-index: 1;
transition: top 160ms ease, left 160ms ease, transform 160ms ease,
opacity 160ms ease;
}
#controller:hover {
@@ -32,14 +39,107 @@
margin-right: 0.8em;
}
/* For center positions, override transform to expand from left edge instead of center.
Exclude manual mode so dragging can freely reposition the controller. */
#controller[data-location="top-center"]:not([data-position-mode="manual"]),
#controller[data-location="bottom-center"]:not([data-position-mode="manual"]) {
transform: translate(0, 0) !important;
left: calc(50% - 30px) !important;
}
#controller[data-location="bottom-center"]:not([data-position-mode="manual"]) {
transform: translate(0, -100%) !important;
}
#controls {
display: none;
}
#controls > * + * {
margin-left: 3px;
}
/* Standalone flash indicator next to speed text — hidden by default,
briefly shown when nudge is toggled via N key or click */
#nudge-flash-indicator {
display: none;
vertical-align: middle;
align-items: center;
justify-content: center;
margin-left: 0.3em;
padding: 3px 6px;
border-radius: 5px;
font-size: 14px;
line-height: 14px;
font-weight: bold;
font-family: "Lucida Console", Monaco, monospace;
box-sizing: border-box;
}
#nudge-flash-indicator.visible {
display: inline-flex;
}
/* Hide flash indicator when hovering — the one in #controls is visible instead */
#controller:hover #nudge-flash-indicator,
:host(:hover) #nudge-flash-indicator {
display: none !important;
width: 0;
height: 0;
margin: 0;
padding: 0;
border: 0;
overflow: hidden;
}
#nudge-flash-indicator[data-enabled="true"] {
color: #fff;
background: #4b9135;
border: 1px solid #6ec754;
}
#nudge-flash-indicator[data-enabled="false"] {
color: #fff;
background: #943e3e;
border: 1px solid #c06060;
}
#nudge-indicator {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 3px 6px;
border-radius: 5px;
font-size: 14px;
line-height: 14px;
font-weight: bold;
font-family: "Lucida Console", Monaco, monospace;
box-sizing: border-box;
cursor: pointer;
margin-bottom: 2px;
}
#nudge-indicator[data-enabled="true"] {
color: #fff;
background: #4b9135;
border: 1px solid #6ec754;
}
#nudge-indicator[data-enabled="false"] {
color: #fff;
background: #943e3e;
border: 1px solid #c06060;
}
#nudge-indicator[data-supported="false"] {
opacity: 0.6;
}
#controller.dragging {
cursor: -webkit-grabbing;
cursor: -moz-grabbing;
opacity: 0.7;
transition: none;
}
#controller.dragging #controls {