Giter VIP home page Giter VIP logo

videojs-hotkeys's Introduction

videojs-hotkeys



Introduction

A plugin for Video.js that enables keyboard hotkeys when the player has focus.

  • Space bar toggles play/pause.
  • Right and Left Arrow keys seek the video forwards and back.
  • Up and Down Arrow keys increase and decrease the volume.
  • M key toggles mute/unmute.
  • F key toggles fullscreen off and on. (Does not work in Internet Explorer, it seems to be a limitation where scripts cannot request fullscreen without a mouse click)
  • Double-clicking with the mouse toggles fullscreen off and on.
  • Number keys from 0-9 skip to a percentage of the video. 0 is 0% and 9 is 90%.

Note: clicking any of the control buttons such as Play/Pause, Fullscreen, or Mute, will remove focus on the player which appears to "break" the hotkeys. This is for accessibility reasons so that people who do not use or know about the hotkeys can still properly use the Tab key to highlight the control buttons and press space to toggle them.

To restore focus, just click on the video, or an empty part of the control bar at the bottom of the video player.

To override this behaviour, set the flag alwaysCaptureHotkeys to true. This will "fix" hotkeys. For accessibility, the Tab key may be used in combination with the Enter/Return key to navigate and activate control buttons.

Empty control bar space

Usage

Include the plugin:

CDN version

You can either load the current release:

<script src="//cdn.sc.gl/videojs-hotkeys/0.2/videojs.hotkeys.min.js"></script>

Or always load the latest version:

<script src="//cdn.sc.gl/videojs-hotkeys/latest/videojs.hotkeys.min.js"></script>

Yarn / npm package

You can install the package:

yarn add videojs-hotkeys
# or npm
npm i videojs-hotkeys --save

Import it into your project:

import "videojs-hotkeys";

Self hosted

<script src="/path/to/videojs.hotkeys.js"></script>

Enable the plugin

Add hotkeys to your Videojs ready function. Check the Options section below for the available options and their meaning.

videojs('vidId', {
  plugins: {
    hotkeys: {
      volumeStep: 0.1,
      seekStep: 5,
      enableModifiersForNumbers: false
    },
  },
});

or

videojs('vidId').ready(function() {
  this.hotkeys({
    volumeStep: 0.1,
    seekStep: 5,
    enableModifiersForNumbers: false
  });
});

Options

  • volumeStep (decimal): The percentage to increase/decrease the volume level when using the Up and Down Arrow keys (default: 0.1)
  • seekStep (integer or function): The number of seconds to seek forward and backwards when using the Right and Left Arrow keys, or a function that generates an integer given the KeyboardEvent (default: 5)
  • enableMute (boolean): Enables the volume mute to be toggle by pressing the M key (default: true)
  • enableVolumeScroll (boolean): Enables increasing/decreasing the volume by scrolling the mouse wheel (default: true)
  • enableHoverScroll (boolean): Only changes volume when the mouse is hovering over the volume control elements. This works in connection with enableVolumeScroll (default: false)
  • enableFullscreen (boolean): Enables toggling the video fullscreen by pressing the F key (default: true)
  • enableNumbers (boolean): Enables seeking the video by pressing the number keys (default true)
  • enableModifiersForNumbers (boolean): Enables the use of Ctrl/Alt/Cmd + Number keys for skipping around in the video, instead of switching browser tabs. This is enabled by default due to backwards compatibility PR #35 (default: true)
  • alwaysCaptureHotkeys (boolean): Forces the capture of hotkeys, even when control elements are focused. The Enter/Return key may be used instead to activate the control elements. (default: false) (Note: This feature may break accessibility, and cause unexpected behavior)
  • enableInactiveFocus (boolean): This reassigns focus to the player when the control bar fades out after a user has clicked a button on the control bar (default: true)
  • skipInitialFocus (boolean): This stops focusing the player on initial Play under unique autoplay situations. More information in Issue #44 (default: false)
  • captureDocumentHotkeys (boolean): Capture document keydown events to also use hotkeys even if the player does not have focus. If you enable this option, you must configure documentHotkeysFocusElementFilter (default: false)
  • documentHotkeysFocusElementFilter (function): Filter function to capture document hotkeys (if captureDocumentHotkeys is enabled) depending on the current focused element. For example, if you want to capture hotkeys when the player is not focused and avoid conflicts when the user is focusing a particular link: documentHotkeysFocusElementFilter: e => e.tagName.toLowerCase() === 'body' (default: () => false)
  • enableJogStyle (boolean): Enables seeking the video in a broadcast-style jog by pressing the Up and Down Arrow keys. seekStep will also need to be changed to get a proper broadcast-style jog. This feature and the changes for seekStep are explained a bit more in PR #12 (default false) (Note: This isn't a feature for everyone, and enabling JogStyle will disable the volume hotkeys)

There are more options specifically for customizing hotkeys described below.

Custom Hotkeys and Overrides

There are 2 methods available here. Simply overriding existing hotkeys, and creating new custom hotkeys.

Override existing hotkeys

Override functions are available for changing which, or adding additional, keys that are used as hotkeys to trigger an action.

Any override functions that you build must return a boolean. true if the matching key(s) were pressed, or false if they were not.

  • playPauseKey (function): This function can be used to override the Play/Pause toggle hotkey (Default key: Space)
  • rewindKey (function): This function can override the key for seeking backward/left in the video (Default key: Left Arrow)
  • forwardKey (function): This function can override the key for seeking forward/right in the video (Default key: Right Arrow)
  • volumeUpKey (function): This function can override the key for increasing the volume (Default key: Up Arrow)
  • volumeDownKey (function): This function can override the key for decreasing the volume (Default key: Down Arrow)
  • muteKey (function): This function can override the key for the volume muting toggle (Default key: M)
  • fullscreenKey (function): This function can override the key for the fullscreen toggle (Default key: F)

These allow you to change keys such as, instead of, or in addition to, "F" for Fullscreen, you can make Ctrl+Enter trigger fullscreen as well. Example usage:

videojs('vidId', {
  plugins: {
    hotkeys: {
      volumeStep: 0.1,
      fullscreenKey: function(event, player) {
        // override fullscreen to trigger when pressing the F key or Ctrl+Enter
        return ((event.which === 70) || (event.ctrlKey && event.which === 13));
      }
    },
  },
});

Create new custom hotkeys

  • customKeys (object): Create an object containing 1 or more sub-objects. Each sub-object must contain a key function and handler function
    • key (function): This function checks if the chosen keys were pressed. It must return a boolean, true if the keys match.
    • handler (function): This function runs your custom code if the result of the key function was true.
videojs('vidId', {
  plugins: {
    hotkeys: {
      volumeStep: 0.1,
      customKeys: {
        // Create custom hotkeys
        ctrldKey: {
          key: function(event) {
            // Toggle something with CTRL + D Key
            return (event.ctrlKey && event.which === 68);
          },
          handler: function(player, options, event) {
            // Using mute as an example
            if (options.enableMute) {
              player.muted(!player.muted());
            }
          }
        }
      }
    },
  },
});

There are more usage examples available in the source code of the example file.


Thanks to BrowserStack for sponsoring cross-browser compatibility and feature testing.

videojs-hotkeys's People

Contributors

ardaogulcan avatar artskydj avatar billybobbonnet avatar boris-petrov avatar chocobozzz avatar coteh avatar ctd1500 avatar edemaine avatar jackocnr avatar jinpark avatar kaizau avatar kernel164 avatar mehanig avatar nhardy avatar omarroth avatar pedrock avatar pettersamuelsen avatar powrsurg avatar steverandy avatar yoonsy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

videojs-hotkeys's Issues

Option to use the Right and Left Arrow keys as chapter navigation

Now the Right and Left Arrow keys only used to seek the video forwards and backwards x seconds.
It would be nice if an option could enable chapter navigation. It could fallback to seek, or do nothing if no chapters track present.
(Heads up for the chapter nav: Chapter 1st's endTime is not always Chapter 2nd's startTime)

BTW, nice work!

MouseWheel changes volume value

Hi, I just realized that when the video player is focused and I use my mousewheel, it changes the video's volume and the page stops scrolling, I tried to change it by overriding the volumeUpKey but look's like it's only executed for arrow keys

Any ideas of how can I avoid this behaviour ?

Thanks in advance, cheers!

Plugin is using deprecated register function

videojs-hotkeys is using videojs.plugin() instead of videojs.registerPlugin(). plugin() is deprecated and may be removed in future versions of videojs, so it would be nice to rewrite it to registerPlugin().

UMD version

Hi,

I use your plugin inside a require.js module application so I need to "requirerize" the plugin.
I think will be good to UMD this plugin. UMD: http://davidbcalhoun.com/2014/what-is-amd-commonjs-and-umd/

You can easily solve this problema wraping your code in:

;(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define([], factory.bind(this, root));
  } else if(typeof module !== 'undefined' && module.exports) {
    module.exports = factory(root);
  } else {
    root.videojsMediaSources = factory(root);
  }

//Plugin starts here
(function(window, videojs) {
   'use strict';
   window['videojs_hotkeys'] = { version: "0.2.8" };

....

// Plugin ends
  videojs.plugin('hotkeys', hotkeys);
})(window, window.videojs);


});

In UMD we can use the plugin as always plus AMD, CommonJS, and UMD.

Regards

Add PictureInPicture hotkey Option

I noticed in your ReadMe page and source code that you didn't have a Picture-In-Picture option.
And I'm a sucker for that accessibility.
In my program, I was sort of able to make one for myself...

customKeys: {
      smallPlayer: {
        key: function(event) {
          return (event.which === 73);
        },
        handler: function(player, options, event) {
          if (player.isInPictureInPicture()) {
            player.exitPictureInPicture();
          } else {
            player.requestPictureInPicture();
          }
        }
      }
    }

I was hoping that you could add a PictureInPicture option in your library to make life easier for those like me.

alwaysCaptureHotkeys bug

Hi,

I tested many versions of videojs and noticed that the alwaysCaptureHotkeys: true option does not work with any version of videojs above 7.5.4
can anyone confirm this?
I think this commit may be related to this
videojs/video.js@79eadac

focus return after submenu (playbackRates/resolutions)

Hi! There is a problem with returning focus after changing something using control-bar submenu. I have a few thoughts on hot to fix this, but I decided to discuss first.

Problem
Plugin trying to return focus to <video> after user interaction with control-bar. This done by determining either active element is inside control-bar or not. Problem that after clicking any submenu focus obviously goes to that submenu. Then when menu fades away videojs wipes it out of DOM and focus goes to <body> so plugin has no chance to determine later did user interacted with control-bar or not. Focus stays at <body> and hotkeys doesn't work =(

Solution 1 (wrong)
Turn on alwaysCaptureHotkeys and give up accessibility

Solution 2 (ugly & non reliable)
add something like this to return focus manually:

player.on 'ratechange', => player.el().focus()
player.on 'resolutionchange', => player.el().focus()

But resolutionchange here is a custom event came from resolution change plugin. Who knows how many plugins can be used

Solution 3
???

Ads/Ima Support

I've been implementing this plugin for our player and noticed that it does not play nicely with ads/ima integrations. I was able to get around this by using the key override functions in the plugin config. This is not the most graceful way to achieve this however. With the above in mind I had a few questions:

  1. Are there plans to support players that are utilizing ads or the ima plugins in order to play ads?
  2. Has there been any thought about not only allowing key overrides, but handler overrides as well? This way something like described above could be handled a little more gracefully through the plugins configuration config.
  3. Have there been any thoughts into updating this plugin to follow the newer es6 plugin standards? In the way that the generator-videojs-plugin provides?

The reason I am asking is because we may be able to provide some PRs for the things listed above since we have had to tackle them internally.

Is there a way to enable disable de plugin?

Is there a way to enable disable de plugin functions?

Because i want to disable it on arrow down and enable on arrow up.
And to enable and disable on my web app when i'm in another view.

Not working in new Chrome 69

As I can test, plugin didn't work in new version of Chrome (69) on MacOS Mojave.
It is strange, but in "private tab" of MacOS Chrome it (plugin) works.
But, as I suppose, plugin didn't work on Windows in Chrome (I received a letter from a user and I believe he uses Windows).

In new Safari 12 it works.

Personally I tested on Windows 10 in Chrome, and for me plugin works.

Uncaught error when pressing fullscreen shortcut with captureDocumentHotkeys set to true and video player focused

Hi, I recently installed v0.2.27 of videojs-hotkeys via npm and I also have v7.7.5 of videojs installed via npm as well (and updated it to 7.11.0 as I was writing this issue). Our team is using video.js as a streaming player in a React project and we are looking to add hotkey support for fullscreen. I stumbled upon this project, which has that and a bunch of other stuff like volume slider and mute hotkey OOTB, all of which would be great to have in our app. One problem I seem to be running into though is an issue where if I enable captureDocumentHotkeys and then press F in Firefox while focusing on the video player, it will throw an Uncaught (in promise) undefined exception, with the following stacktrace:

errorHandler video.es.js:23691
errorHandler self-hosted:1161
func video.es.js:2084
dispatcher video.es.js:1898
(Async: EventListener.handleEvent)
on video.es.js:1918
one video.es.js:2089
listen video.es.js:2666
one video.es.js:2780
requestFullscreen video.es.js:23695
requestFullscreen video.es.js:23678
q videojs.hotkeys.min.js:2
q self-hosted:1161
dispatcher video.es.js:1898
(Async: EventListener.handleEvent)
on video.es.js:1918
listen video.es.js:2666
on video.es.js:2716
Player video.es.js:21373
videojs$1 video.es.js:26730
Streaming Streaming.tsx:261 (this is the line where videojs is initialized)

I threw in a console.log inside the documentHotkeysFocusElementFilter callback I passed into hotkeys options and I notice that two logs are printed when I press F while focused on video player, but when I'm not focused on the element, only one log is printed.

Also, in Chrome, I get the following message alongside the error: Failed to execute 'requestFullscreen' on 'Element': API can only be initiated by a user gesture.

The following is how I initialized the hotkeys plugin if that helps:

player.ready(function() {
    this.hotkeys({
        enableNumbers: false,
        captureDocumentHotkeys: true,
        documentHotkeysFocusElementFilter: e => e.tagName.toLowerCase() === "body",
        rewindKey: () => false,
        forwardKey: () => false,
        playPauseKey: () => false,
    });
});

Let me know if there's anything here that I need to change, thanks.

(also, as a sidenote, mute hotkey does not work for me in Chrome)

0.2.25 does not work for player versions such as 6.13.0, 7.3.0, 7.5.0

Hello! Release 0.2.25 does not work for player versions such as 6.13.0, 7.3.0, 7.5.0
Only in the browser firefox works. What could be the reason ? The script is connected and everything is written without changes. On the version of the player 5.20.5 works fine! Thanks in advance!

$(document).ready(function() {
videojs('player1').ready(function() {
this.hotkeys({
volumeStep: 0.1,
seekStep: 5,
enableMute: true,
enableVolumeScroll: true,
enableFullscreen: true,
enableNumbers: true,

	});  
});

});

Page scroll on focus issue

When video paused and page is scrolled where the player is not visible, code for setting focus to the controlbar in userinactive event cause page to scroll up to the video again.

IE11 flash

I just cannot use any function of this plugin with flash in IE11 while it works with flash in firefox.

after update not work

Hi! Help council ! Updated plugin hotkeys. My Site : http:// template unchanged, but hotkeys are not working again. Self Hosted in main.tpl :
script src="//
initialization script in end of file libs.js :

Hotkeys disabled when control buttons focused

@ctd1500

This particular line disables hotkeys: https://github.com/ctd1500/videojs-hotkeys/blob/master/videojs.hotkeys.js#L71

The comment above this section suggests an option to disable this behaviour, but there is no option available.
The comment suggests disabling is possible if in jogStyle mode, but this does not seem like the correct name for such a control. Perhaps a new option is required?

One particular example:
User clicks fullscreen button, then presses spacebar to pause.

Expected behaviour:
Video goes fullscreen, then is paused.

Actual behaviour:
Video goes fullscreen, then exits fullscreen.

I am able to submit a PR which fixes the issue if required.

Doesn't work with the latest video.js (export/import issue)

The issue seems to be quite simple; video.js changed how they expose their lib at some point (?) so the code

import videojs from 'video.js';
require('videojs-hotkeys');

would yield Uncaught TypeError: (e.registerPlugin || e.plugin) is not a function;

It seems that this is because var registerPlugin = videojs.registerPlugin || videojs.plugin; in videojs-hotkeys/videojs.hotkeys.js evaluates into undefined because videojs object there has .default property now that is supposed to be called instead.

A code like

var vjs = videojs.default || videojs;
var registerPlugin = vjs.registerPlugin || vjs.plugin;

would fix the issue but I'm not sure if It fixes the real problem instead of "symptoms"

hotkey dose not work in userinactive state.

Normally hotkey works well.

Except below case.
How to reproduce bug

  1. play video.
  2. press any hot key. (works well)
  3. click any focusable control button.
  4. wating some secs.
  5. controlbar is disappeared because of user are in userinactive state.
  6. the document.activeElement is changed to document.body.
  7. hotkey dose not work anymore.
player.on('userinactive', function() {
  pEl.focus();
});

Maybe, this could be a solution.

dont work plagin!

This plagin dont work/
Inserted it anywhere already. Works nothing. Any plugin for this player not the worker.
Enable the plugin

Add hotkeys to your Videojs ready function.

videojs (' vidId ').ready (function () {
this.hotkeys ({
volumeStep: 0.1,
seekStep: 5,
enableMute: true,
enableFullscreen: true
});
});

Bug when clicking on pause

Hi, today I just discovered a bug with this hotkeys plugin for video.js

If you play a video, then pause and then scroll down, after 3-4 seconds you will be automatically scrolled up
I'm using:

// package.json
{
       "video.js": "^5.17.0",
       "videojs-hotkeys": "^0.2.17",
}

I'm wondering if anyone else has experienced this behavior.

`videojs.mergeOptions` is deprecated

VIDEOJS: WARN: videojs.mergeOptions is deprecated and will be removed in 9.0; please use videojs.obj.merge instead.

Possible fix for videojs.hotkeys.js:

// Use built-in merge function
var mergeOptions = 'obj' in videojs
  ? videojs.obj.merge         // Video.js > v9
  : (videojs.mergeOptions ||  // Video.js >= v5
    videojs.util.mergeOptions // Video.js <= v4
  );

OR

Use videojs.obj.merge directly (remove the support of Video.js < v9)

Never let the player get focus

Hi there,

I have an issue where the player gets focus when alwaysCaptureHotkeys is set to false and autoplay is active. This means that the page will jump to the player on pageload if autoplay is active.

This happens because we handle autoplay in a different way in order to do certain detections before we 'autoplay' the video. In short this causes autoplay to be set to false when the player gets initialized, while still starting the video, and therefor it passes the following if statement of the hotkeys code:

if (alwaysCaptureHotkeys || !player.autoplay()) {
      player.one('play', function() {
        pEl.focus(); // Fixes the .vjs-big-play-button handing focus back to body instead of the player
      });
 }

Is it possible to get an option created where we can set the player to never get focus? Something like neverAllowFocus for example. which will ignore this whole if statement if set to true?

Thanks in advance

default page scroll not working

Hi,

i enabled hotkeys plugin with

this.hotkeys({
          volumeStep: 0.1,
          seekStep: 5,
          enableModifiersForNumbers: false,
          alwaysCaptureHotkeys: true

        });

When i scroll mouse wheel on the video, before clicking on the play icon, page scroll should work.
But seems the page is there in the same place.
When I removed the hotkeys, page scroll working fine on the video.

Toggle Mute handler code

Hi,

You can change this code:

   // Toggle Mute with the M key
        case 'mute':
          if (enableMute) {
            if (player.muted()) {
              player.muted(false);
            } else {
              player.muted(true);
            }
          }
          break;

Reduced code:

if (enableMute) {
    player.muted(!player.muted());
}

[bug] Spacebar hotkey only works every other time hotkeys() is called

Summary of Problem

On a page that triggeres multiple videos, the hotkeys work perfectly on the first video. However spacebar only works EVERY OTHER TIME. How do you force the SPACE hotkey to work reliably?

Steps to reproduce

  1. Open https://jsfiddle.net/o82kw4jg/1/ in Chrome OSX (untested in Windows)
  2. Click one of the 1-5 buttons to trigger a video.
  3. It works great ... you can hit SPACEBAR, arrows to skip, and numbers to jump.
  4. Now click any of the 1-5 buttons (same or different) to trigger another video.
  5. Arrows work, numbers work, but SPACEBAR does not.
  6. Click a 1-5 button
  7. SPACEBAR works again.

Expected behaviour

Spacebar always plays/pauses the video, regardless of focus.

Actual behaviour

Spacebar only works every other time.

The play() request was interrupted by a call to pause().

Hi, thanks for the great plugin!

We're getting the exception in the title on Chrome. It's very easy to reproduce - just play a video and hold the "right" arrow key on your keyboard and it happens. Google has a bunch of documentation written about that. The problem is that the call to play here is asynchronous and the check whether the video is playing that is done here returns true before the play call is actually finished and then the pause method call causes that exception. play returns a promise in which it is safe to call pause.

I'm not sure whether this is a bug in Chrome/Video.js/Video.js-Hotkeys, that's probably for you to say.

Hotkeys between slider page

Good Night, im using flexslider 2 to show video between sliders, and hotkeys script dont work between them, can anyone help me?

Performance issue on Chrome

Adding tabindex on player element makes the player a lot less responsive (lots of drop frame) unless outline is specifically deactivated in CSS.

The problem is specifically on chrome. Confirmed on Mac and Windows 10. Edge, Safari and Firefox doesn't seem to have issues with it.

My fix for my use case is this:

:focus  {outline:none;}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.