Why do you think it is necessary to insert an autoplay video on your website?

The web is in a dark place, as I plan to examine in the next several columns. If you need proof, look no further than autoplay videos, the first example.

You’re probably familiar with this horrendous experience: You are perusing a website, and suddenly an annoying voice or unfamiliar music blasts through your speakers.

You wonder, where is this coming from? You scroll up and down the webpage only to realize that a video is playing without your consent. And the noise polluting your ears is coming from an ad preceding a video you had never clicked to watch.

Autoplay videos are all over the web and inside apps. They are prominent in your Facebook and Instagram feeds. Some major news sites embed them into features and news articles.

Nobody seems to likes autoplay videos — not even people I’ve talked to in the ad industry. The indiscreet videos demand your attention while burning through your mobile data plan and sucking up your batteries. Yet they have become a necessary evil for many media publishers trying to survive in the digital age.

“I think we’ve ended up in a really crappy user experience right now with video advertising,” said Dave Morgan, the chief executive of Simulmedia, which works with advertisers on targeted television ads. “Video has been pushed into every user experience whether or not it fits, because it’s a way to make more money.”

Well, I come here bearing some good news and bad news about these abominations. The bad news is that autoplay videos are here to stay, and that the tools to combat them are far from perfect. The good news is that they are evolving to be less annoying, and that some sites let you turn them off. Here’s what you need to know about how we got here, what you can do and where autoplay videos are heading.

In digital media, video advertising was always the ultimate goal. Twenty years ago, web publishers dreamed of delivering video ads online: It was the perfect format, already proved by the TV industry to be engaging to audiences and a big revenue generator.

“Sight, sound and motion can make people laugh, make people cry, make them hug somebody,” Mr. Morgan said. “It can make them love a brand. It can make them whistle a brand’s theme song when they’re walking a dog.”

Yet publishers faced technical hurdles, like slow internet connections, that made video ads untenable. Instead, publishers served ads that were static images, which eventually evolved to become graphics with some animations and sound.

Over the last decade, fast wired and wireless connections spread, as did computers and smartphones. Consumers also became acclimated to streaming video services like Netflix and YouTube. Serving an online video became easy. So advertising firms like BrightRoll and Tremor Video, along with tech companies like Facebook, began testing video ads.

Once they got started, there was no turning back. Video ads generated 20 to 50 times more revenue than traditional display ads, and the best way to get money was to make the videos play automatically, Mr. Morgan said. Tech platforms like Facebook and Twitter liked autoplay videos, too, because they were effective at getting people to stick around on their sites, said Taylor Wiegert, a director of user experience strategy for the Martin Agency. Automatically playing videos went from a rarity a decade ago to a prominent online advertising medium today.

Many consumers have complained that autoplay videos are a nuisance. [I am one of them!] So tech companies have come up with some workarounds:

Facebook and Twitter each offer the ability to prevent videos from automatically playing in their apps and websites. On Facebook, the instructions are buried in its Accessibility page, and on the Twitter website, the controls are found in the Settings menu, under Content.

On Instagram, you cannot disable videos from automatically playing. However, in the cellular data setting, you can configure the app to use less mobile data, which makes videos load more slowly when you are on a cellular connection.

Google’s Chrome browser prevents some videos from automatically playing. The web browser allows videos to autoplay on 1,000 sites where Google has determined that people have the highest likelihood of wanting to play videos with sound. Over time, after Chrome studies the websites that you visit, the browser adapts to allow autoplaying on sites where you frequently played videos with the sound on and disables autoplay on sites where you do not.

Some software developers offer browser add-ons that prevent all videos from automatically playing. But the tools are imperfect: A Chrome add-on that I tested, for example, blocked videos when I was doing a videoconference on Google Hangouts.

As annoying as they may be, autoplay videos are here to stay — largely because the ads generate so much money. But they are thankfully becoming less obnoxious.

Increasingly, advertising firms are shifting toward making autoplay videos with the assumption that people have muted their devices. Mr. Wiegert of the Martin Agency said his firm primarily makes ads with sound off by default. It designs them to communicate a company’s branding and message without requiring sound.

Tech companies, too, are evolving their products to make autoplay videos less of a nuisance. For example, Google says that part of its criteria for allowing autoplay to work in the Chrome browser is for the videos to be muted or have no sound. And on Instagram, automatically played videos are muted by default unless you manually turn on the audio.

“Autoplay with sound on is just going to go extinct,” Mr. Wiegert said. “It’s been deemed as a poor quality experience for users. Even I’ve gotten annoyed when I’ve been on a webpage and all of a sudden I hear sound coming through my speakers.”

Yet Mr. Morgan of Simulmedia believes video ads will be forced to change more radically to give people fuller control over what they see. That’s because autoplay videos still satisfy publishers, not the consumers.

“We’re putting those ads in those places because we can — not because it is the best for the user,” he said.

Automatically starting the playback of audio [or videos with audio tracks] immediately upon page load can be an unwelcome surprise to users. While autoplay of media serves a useful purpose, it should be used carefully and only when needed. In order to give users control over this, browsers often provide various forms of autoplay blocking. In this guide, we'll cover autoplay functionality in the various media and Web Audio APIs, including a brief overview of how to use autoplay and how to work with browsers to handle autoplay blocking gracefully.

Autoplay blocking is not applied to elements when the source media does not have an audio track, or if the audio track is muted. Media with an active audio track are considered to be audible, and autoplay blocking applies to them. Inaudible media are not affected by autoplay blocking.

The term autoplay refers to any feature that causes audio to begin to play without the user specifically requesting that playback begin. This includes both the use of HTML attributes to autoplay media as well as the user of JavaScript code to start playback outside the context of handling user input.

That means that both of the following are considered autoplay behavior, and are therefore subject to the browser's autoplay blocking policy:

and

The following web features and APIs may be affected by autoplay blocking:

  • The HTML and elements
  • The Web Audio API

From the user's perspective, a web page or app that spontaneously starts making noise without warning can be jarring, inconvenient, or off-putting. Because of that, browsers generally only allow autoplay to occur successfully under specific circumstances.

As a general rule, you can assume that media will be allowed to autoplay only if at least one of the following is true:

  • The audio is muted or its volume is set to 0
  • The user has interacted with the site [by clicking, tapping, pressing keys, etc.]
  • If the site has been allowlisted; this may happen either automatically if the browser determines that the user engages with media frequently, or manually through preferences or other user interface features
  • If the autoplay feature policy is used to grant autoplay support to an and its document.

Otherwise, the playback will likely be blocked. The exact situations that result in blocking, and the specifics of how sites become allowlisted vary from browser to browser, but the above are good guidelines to go by.

For details, see the auto-play policies for Google Chrome and WebKit.

Note: Put another way, playback of any media that includes audio is generally blocked if the playback is programmatically initiated in a tab which has not yet had any user interaction. Browsers may additionally choose to block under other circumstances.

Now that we've covered what autoplay is and what can prevent autoplay from being allowed, we'll look at how your web site or app can automatically play media upon page load, how to detect when autoplay fails to occur, and tips for coping when autoplay is denied by the browser.

The simplest way to automatically play content is to add the autoplay attribute to your or element. This sets the autoplay property on the element to true, and when autoplay is true, the media will automatically begin to play as soon as possible after the following have occurred:

  • The page is allowed to use autoplay functionality
  • The element has been created during page load
  • Enough media has been received to begin playback and continue to play through to the end of the media without interruption, assuming there are no dramatic changes in network performance or bandwidth.

Example: The autoplay attribute

An element using the autoplay attribute might look like this:

Example 2: Detecting autoplay failure

If you rely on autoplay for anything important, or if autoplay failure will impact your app in any way, you will probably want to be able to tell when it autoplay didn't begin. Unfortunately, in the case of the autoplay attribute, recognizing whether or not autoplay successfully began is tricky. There's not an event triggered when autoplay fails. Nor is there an exception thrown or a callback you can set up or even a flag on the media element that tells you if autoplay worked. All you can really do is examine a few values and make an educated guess as to whether or not autoplay worked.

A better approach, if you're able to adjust the direction you look at things from, is to instead rely on knowing that playback of the media has successfully started, instead of when it fails to start. You can do this easily, by listening for the play event to be fired on the media element.

The play event is sent both when the media is resumed after being paused and when autoplay occurs. That means that the first time the play event is fired, you know your media is being started for the first time after the page is opened.

Consider this HTML for a media element:

Here we have a element whose autoplay attribute is set, with an onplay event handler set up; the event is handled by a function called handleFirstPlay[], which receives as input the play event.

handleFirstPlay[] looks like this:

let hasPlayed = false; function handleFirstPlay[event] { if[hasPlayed === false] { hasPlayed = true; let vid = event.target; vid.onplay = null; } }

After getting a reference to the video element from the Event object's target, the element's onplay handler is set to null. This will prevent any future play events from being delivered to the handler. That could happen if the video is paused and resumed by the user or automatically by the browser when the document is in a background tab.

At this point, your site or app can begin whatever it needs to do that relies upon the video having been started up.

Note: This approach doesn't differentiate between autoplay and the user starting playback manually.

The term "autoplay" also refers to scenarios in which a script tries to trigger the playback of media that includes audio, outside the context of handling a user input event. This is done by calling the media element's play[] method.

Note: It is strongly recommended that you use the autoplay attribute whenever possible, because support for autoplay preferences are more widespread for the autoplay attribute than for other means of playing media automatically. It also lets the browser take responsibility for starting playback, letting it optimize the timing of that taking place.

Example: Playing video

This simple example plays the first element found in the document. play[] won't let the playback begin unless the document has permission to automatically play media.

document.querySelector["video"].play[];

Example: Handling play[] failures

It's much easier to detect a failure to autoplay media when you use the play[] method to start it. play[] returns a Promise which is resolved once the media successfully begins to play, and is rejected when playback fails to begin [such as if autoplay is denied]. When autoplay fails, you likely will want to offer a way for the user to manually tell the browser to ask the user to grant permission to play media.

You might use code like this to accomplish the job:

let startPlayPromise = videoElem.play[]; if [startPlayPromise !== undefined] { startPlayPromise.then[[] => { }].catch[error => { if [error.name === "NotAllowedError"] { showPlayButton[videoElem]; } else { } }]; }

The first thing we do with the result of play[] is make sure it's not undefined. We check for this because in earlier versions of the HTML specification, play[] didn't return a value. Returning a promise to allow you to determine success or failure of the operation was added more recently. Checking for undefined prevents this code from failing with an error on older versions of web browsers.

If the promise returned by play[] is resolved without error, the then[] clause is run and can begin whatever needs to be done when autoplay has begun.

We then add a catch[] handler to the promise. This looks at the error's name to see if it's NotAllowedError. This indicates that playback failed due to a permission issue, such as autoplay being denied. If that's the case, we should present a user interface to let the user manually start playback; that's handled here by a function showPlayButton[].

Any other errors are handled as appropriate.

If you want to start playing the video after the first interaction with the page, setInterval[] might be used to achieve this:

let playAttempt = setInterval[[] => { videoElem.play[] .then[[] => { clearInterval[playAttempt]; }] .catch[error => { console.log['Unable to play the video, User has not interacted yet.']; }]; }, 3000];

In the Web Audio API, a web site or app can start playing audio using the start[] method on a source node linked to the AudioContext. Doing so outside the context of handling a user input event is subject to autoplay rules.

More content will come soon; autoplay blocking is still being worked on at Mozilla. If others have it already, they are welcome to pitch in with this section...

In addition to the browser-side management and control over autoplay functionality described above, a web server can also express its willingness to allow autoplay to function. The HTTP Feature-Policy header's autoplay directive is used to control which domains, if any, can be used to autoplay media. By default, the autoplay feature policy is set to 'self' [including the single quote characters], indicating that autoplay is permitted as they're hosted on the same domain as the document.

You can also specify 'none' to disable autoplay entirely, '*' to allow autoplay from all domains, or one or more specific origins from which media can be automatically played. These origins are separated by space characters.

Note: The specified feature policy applies to the document and every nested within it, unless those frames include an allow, which sets a new feature policy for that frame and all frames nested within it.

When using the allow attribute on an to specify a feature policy for that frame and its nested frames, you can also specify the value 'src' to allow autoplay of media only from the same domain as that specified by the frame's src attribute.

To use the Feature-Policy header to only allow media to autoplay from the document's origin:

Feature-Policy: autoplay 'self'

To do the same for an :

Adding Fullscreen API permission to the previous example results in a Feature-Policy header like the following if fullscreen access is allowed regardless of the domain; a domain restriction can be added as well as needed.

Feature-Policy: autoplay 'self'; fullscreen

The same permissions, grated using the element's allow property, look like this:

The Feature-Policy header to allow media to be played from both the document's [or 's] own domain and //example.media looks like this:

Feature-Policy: autoplay 'self' //example.media

An can be written to specify that this autoplay policy should be applied to itself and any child frames would be written thusly:

Setting the autoplay feature policy to 'none' disables autoplay entirely for the document or and all nested frames. The HTTP header is:

Feature-Policy: autoplay 'none'

Using the 's allow attribute:

Tips and recommended best practices to help you make the most of working with autoplay are offered here.

A common use case for autoplay is to automatically begin to play a video clip that goes along with an article, an advertisement, or a preview of the page's main functionality. To autoplay videos like these, you have two options: don't have an audio track, or have an audio track but configure the element to mute the audio by default, like this:

This video element is configured to include the user controls [typically play/pause, scrubbing through the video's timeline, volume control, and muting]; also, since the muted attribute is included, and the playsinline attribute that is required for autoplay in Safari, the video will autoplay but with the audio muted. The user has the option, however, of re-enabling the audio by clicking on the unmute button in the controls.

Browsers may have preferences that control the way autoplay works, or how autoplay blocking is handled. Here, any such preferences that may be of special significance or importance to you as a web developer are listed. These include any that may aid in testing or debugging as well as any that could be set in a way that you need to be prepared to handle.

media.allowed-to-play.enabled

A Boolean preference which specifies whether or not the HTMLMediaElement.allowedToPlay property is exposed to the web. This is currently false by default [except in nightly builds, where it's true by default]. If this is false, the allowedToPlay property is missing from the HTMLMediaElement interface, and is thus not present on either or elements.

media.autoplay.allow-extension-background-pages

This Boolean preference, if true, allows browser extensions' background scripts to autoplay audio media. Setting this value to false disables this capability. The default value is true.

media.autoplay.allow-muted

A Boolean preference which if true [the default] allows audio media which is currently muted to be automatically played. If this has been changed to false, media with an audio track will not be permitted to play even if muted.

media.autoplay.block-webaudio

A Boolean preference which indicates whether or not to apply autoplay blocking to the Web Audio API. The default is false, except on Nightly where it is true.

media.autoplay.default

An integer preference which specifies whether per-domain configuration for autoplay support by default is allowed [0], blocked [1], or prompt-on-use [2]. The default value is 0.

media.autoplay.enabled.user-gestures-needed [Nightly builds only]

A Boolean preference which controls whether or not detection of user gestures is allowed to override the setting of media.autoplay.default. If media.autoplay.default is not set to 0 [autoplay allowed by default], this preference being true allows autoplay of media with audio tracks anyway if the page has been activated by user gestures, and media that isn't audible is not restricted at all.

media.block-autoplay-until-in-foreground

A Boolean preference which indicates whether or not media playback is blocked when started on a background tab. The default value, true, means that even when otherwise available, autoplay won't take place until after a tab is brought to the foreground. This prevents the distracting situation in which a tab begins playing sound and the user can't find the tab among all their tabs and windows.

Video liên quan

Chủ Đề