How to embed an autoplaying YouTube video in an iframe?

文章推薦指數: 80 %
投票人數:10人

I am trying to embed the new iframe version of a YouTube video and get it to auto play. As far as I can tell, there is no way of doing this by ... Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore HowtoembedanautoplayingYouTubevideoinaniframe? AskQuestion Asked 10years,2monthsago Active 1year,4monthsago Viewed 863ktimes 239 37 IamtryingtoembedthenewiframeversionofaYouTubevideoandgetittoautoplay. AsfarasIcantell,thereisnowayofdoingthisbyamendingflagstotheURL.IsthereawaytodoitbyusingJavaScript&theAPI? javascripthtmliframeyoutubeyoutube-api Share Follow editedAug12'19at18:24 TylerH 19.9k5555goldbadges6868silverbadges8989bronzebadges askedSep2'11at9:50 472084472084 17.2k1010goldbadges5959silverbadges8080bronzebadges 2 Isthereawaytomutethesoundwhenthevideostartsplaying,throughcode,Idon'twanttosurprisemyuserswithsound – danielmetlitski May24'17at11:57 Browserhassettingsforthat – HossamMaher May31at13:05 Addacomment  |  14Answers 14 Active Oldest Votes 442 ThisworksinChromebutnotFirefox3.6(warning:RickRollvideo): TheJavaScriptAPIforiframeembedsexists,butisstillpostedasanexperimentalfeature. UPDATE:TheiframeAPIisnowfullysupportedand"CreatingYT.Playerobjects-Example2"showshowtoset"autoplay"inJavaScript. Share Follow editedOct24'12at15:15 answeredSep2'11at16:31 mjhmmjhm 15.9k99goldbadges4242silverbadges5555bronzebadges 6 2 Hint:Onmobiledevicesit'spossibleboththesrcparameterandtheapicallwillnotworkduetorestrictions:developers.google.com/youtube/… – LinusCaldwell Nov8'14at23:25 Ifindthatonmobile(WebviewonAndroid5.0)thefunctiononYouTubeIframeAPIReady()isn'ttriggered.Anyonehaveasolution? – SomeoneSomewhere Jan19'15at19:08 2 Isthereawaytomutethesoundwhenthevideostartsplaying,throughcode,Idon'twanttosurprisemyuserswithsound – danielmetlitski May24'17at11:57 stackoverflow.com/questions/48086769/…@JoJo – MattAllegro May17'18at9:41 7 Youmayalsoneed:allow="autoplay"foryouriFrame – Jeffz Jun4'18at20:49  |  Show1morecomment 57 SinceApril2018,GooglemadesomechangestotheAutoplayPolicy.Younotonlyneedtoaddtheautoplay=1asaqueryparam,butalsoaddallow='autoplay'asaniframe'sattribute Soyouwillhavetodosomethinglikethis: Share Follow editedJul13'20at13:32 answeredJul4'18at18:32 MatayoshiMarianoMatayoshiMariano 1,7461616silverbadges2222bronzebadges 3 autoplay=1asparamterisnotenough(timeofwritingJuly20).I'dtoaddallow='autoplay'totheiframetogettheautoplayfeatureworking. – Gkiokan Jul9'20at11:55 @GkiokanYep,uneedthat.Ihadthatinthesnippet:) – MatayoshiMariano Jul9'20at16:29 1 Yea,IwantedtomakeitcleartotheothersthatthesolutionisnotonlytheparamintheURLbutalsotheextraparameter:)Maybeyoushouldmentionthatexplicit. – Gkiokan Jul13'20at7:20 Addacomment  |  40 Theembeddedcodeofyoutubehasautoplayoffbydefault.Simplyaddautoplay=1attheendof"src"attribute.Forexample: Share Follow editedAug13'13at20:26 develCuy 47055silverbadges1212bronzebadges answeredJan23'13at17:19 WaheedurRehmanWaheedurRehman 75566silverbadges1313bronzebadges 2 3 add?autoplay=1tothesrc – Squirrl Jun17'16at23:20 1 yesactuallyautoplay=1while?indicatesrcmayhaveparameterslikecolor,controlsandeachseparatedby&sign.detaildescriptioncanbeseenheredevelopers.google.com/youtube/player_parameters#Parameters – WaheedurRehman Jun19'16at0:12 Addacomment  |  34 August2018Ididn'tfindaworkingexampleontheiframeimplementation. OtherquestionswererelatedtoChromeonly,whichgaveitawayalittle. You'llhavetomutesoundmute=1inordertoautoplayonChrome.FFandIEseemtobeworkingjustfineusingautoplay=1asparameter. Share Follow answeredAug14'18at12:17 TimVermaelenTimVermaelen 6,25611goldbadge2222silverbadges3636bronzebadges 3 2 Mosthelpfulanswerbyfar.Makessense. – robbclarke Jan7at13:23 Thankyousomuchfortheanswer,buthowcouldIunmutethevideoafterautoplayingit? – Pyzard Oct4at8:13 Thepointisit'simpossibleprogrammaticallyforembeddedvideos.Tounmute,auserincreasesthevolumeonhisplayer.Atthatpointhisconsentisgiventoevenplayaudio. – TimVermaelen Oct4at12:24 Addacomment  |  12 2014iframeembedonhowtoembedayoutubevideowithautoplayandnosuggestedvideosatendofclip rel=0&autoplay ExampleBelow:. Share Follow editedJul11'18at11:10 Victoria 7,54722goldbadges1919silverbadges4343bronzebadges answeredMay5'14at21:41 RalphRalph 12911silverbadge22bronzebadges Addacomment  |  11 attheendoftheiframesrc,add&enablejsapi=1toallowthejsAPItobeusedonthevideo andthenwithjquery: jQuery(document).ready(function($){ $('.video-selectoriframe')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}','*'); }); thisshouldplaythevideoautomaticallyondocument.ready note,thatyoucouldalsousethisinsideaclickfunctiontoclickonanotherelementtostartthevideo Moreimportantly,youcannotauto-startvideosonamobiledevicesouserswillalwayshavetoclickonthevideo-playeritselftostartthevideo Edit: I'mactuallynot100%sureondocument.readytheiframewillbeready,becauseYouTubecouldstillbeloadingthevideo.I'mactuallyusingthisfunctioninsideaclickfunction: $('.video-container').on('click',function(){ $('video-selectoriframe')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}','*'); //addothercodeheretoswapacustomimage,etc }); Share Follow editedJul15'15at15:11 answeredJul15'15at14:27 bdaninbdanin 73377silverbadges99bronzebadges 3 1 Utilizingthisanswer,andwrappingthejQueryselectorinasetTimeoutworkedforme. – tyler.frankenstein Apr18'16at13:37 1 Samehere,justfiretheeventseveraltimeseverysecondanditwillwork. – MatthiasKleine Jun18'17at7:11 Itisnotaboutfiringtheeventfrequently!YouTubehadrecentlyupdatedtheirpolicyonautoplayingembeddedvideos.ThenewpolicyisthatavideoCANNOTbeautoplayeduntilthereisarealuserinteractiononthepage(clicking,scrolling...).Ithinkthatinyourcasesinceyou'refiringthecodeeverysecond,thecodejustrunnormallyafterthefirstuserinteraction,soyou'dthinkthatthereasonisthefrequentfiringoftheevent!Nevertheless,itisNOTagoodpracticetofireacodelikethiseverysecond! – AhmedEl-Atab Sep23at22:52 Addacomment  |  6 Theflags,orparametersthatyoucanusewithIFRAMEandOBJECTembedsaredocumentedhere;thedetailsaboutwhichparameterworkswithwhatplayerarealsoclearlymentioned: YouTubeEmbeddedPlayersandPlayerParameters Youwillnoticethatautoplayissupportedbyallplayers(AS3,AS2andHTML5). Share Follow answeredNov15'12at22:33 SalmanASalmanA 238k7878goldbadges405405silverbadges498498bronzebadges Addacomment  |  6 Multiplequeriestipforthosewhodon'tknow(pastmeandfutureme) Ifyou'remakingasinglequerywiththeurljust?autoplay=1worksasshownbymjhm'sanswer Ifyou'remakingmultiplequeriesrememberthefirstonebeginswitha?whiletherestbeginwitha& Sayyouwanttoturnoffrelatedvideosbutenableautoplay... Thisworks andthisworks Butthesewon'twork.. examplecomparisons https://jsfiddle.net/Hastig/p4dpo5y4/ moreinfo ReadNextLocal'sreplybelowformoreinfoaboutusingmultiplequerystrings Share Follow editedMay23'17at10:31 CommunityBot 111silverbadge answeredAug30'16at1:25 HastigZusammenstellenHastigZusammenstellen 3,92222goldbadges2929silverbadges4444bronzebadges 6 1 Thereasonyoursdidn'tworkisbecauseyoualreadyhad?rel=0inthere.Ifyouremovedthatitwouldhaveworked.Readmoreaboutquerystringsyntaxhereifyou'dlike.?rel=0?autoplay=1shouldbeeither?autoplay=1or?rel=0&autoplay=1 – jaggedsoft Oct2'16at20:12 @NextLocalThanks,I'llcomebacktothisandedit/deletemyanswernexttimeI'mworkingonsomethingthatiframesyoutubevideos. – HastigZusammenstellen Oct3'16at1:20 theexampleyou'reprovidinghttp://www.youtube.com/embed/oHg5SJYRHA0&autoplay=1definitelywon'twork,buthttps://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1should – jaggedsoft Oct3'16at20:00 @NextLocalHa,Igotitnow.NotsurehowIdidn'trealizethat:DThanksagain. – HastigZusammenstellen Oct4'16at4:27 Isthereawaytomutethesoundwhenthevideostartsplaying,throughcode,Idon'twanttosurprisemyuserswithsound – danielmetlitski May24'17at11:58  |  Show1morecomment 3 TohavetheacceptedanswerbymjhmworkingonChrome66inMay2018,Iaddedallow=autoplaytotheiframeandenable_js=1tothequerystring: Share Follow answeredMay17'18at9:59 MattAllegroMattAllegro 4,88255goldbadges3636silverbadges4747bronzebadges 0 Addacomment  |  3 NowadaysIincludeanewattribute"allow"oniframetag,forexample: allow="accelerometer;autoplay;encrypted-media;gyroscope; picture-in-picture" Thefinalcodeis: Share Follow answeredDec6'19at21:15 JonasWebDevJonasWebDev 32522silverbadges1212bronzebadges 2 1 worksatrick!Icouldn'tfigureoutwhypageloadswereonlyshowingthevideosometimesandnotothertimes! – shaneonabike Jan29'20at20:46 Haveallthatbutstillnotworking:( – BVernon Sep24at22:46 Addacomment  |  1 1-add&enablejsapi=1toIFRAMESRC 2-jQueryfunc: $('iframe#your_video')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}','*'); Worksfine Share Follow editedJun21'16at14:22 Vasfed 17k1010goldbadges4646silverbadges5050bronzebadges answeredJun21'16at14:16 GabrielMoraisGabrielMorais 1922bronzebadges 1 1 Inmycaseitworksfromtheconsole,orwhenIalreadyinteractedwiththevideomanually.Doesn'tworkonload,eventimed-out – mate.gvo Jul6'18at17:03 Addacomment  |  0 Tousejavascriptapi, YouneedFlashplayer8+andJavaScriptenabledtoviewthisvideo. varparams={allowScriptAccess:"always"}; varatts={id:"myytplayer"}; swfobject.embedSWF("http://www.youtube.com/v/OyHoZhLdgYw?enablejsapi=1&playerapiid=ytplayer&version=3", "ytapiplayer","425","356","8",null,null,params,atts); Toplaytheyoutubewiththeid: swfobject.embedSWF reference:https://developers.google.com/youtube/js_api_referencemagazine Share Follow answeredMar11'15at7:41 HTML5developerHTML5developer 22933silverbadges22bronzebadges Addacomment  |  0 Share Follow editedSep30'17at20:12 PaulRoub 35.4k2727goldbadges7777silverbadges8787bronzebadges answeredSep30'17at19:25 GeorgeSarievGeorgeSariev 6544bronzebadges Addacomment  |  0 December2018, LookingforanAUTOPLAY,LOOP,MUTEyoutubevideoforreact. Otheranswersdidn'tworked. Ifoundasolutionwithalibrary:react-youtube classVideoextendsComponent{ _onReady(event){ //addmute event.target.mute(); //addautoplay event.target.playVideo(); } render(){ constopts={ width:'100%', height:'700px', playerVars:{ //removevideocontrols controls:0, //removerelatedvideo rel:0 } }; return( ) } } Share Follow answeredDec20'18at21:00 DavideCarpiniDavideCarpini 1,2351313silverbadges1313bronzebadges Addacomment  |  Highlyactivequestion.Earn10reputation(notcountingtheassociationbonus)inordertoanswerthisquestion.Thereputationrequirementhelpsprotectthisquestionfromspamandnon-answeractivity. Nottheansweryou'relookingfor?Browseotherquestionstaggedjavascripthtmliframeyoutubeyoutube-apioraskyourownquestion. TheOverflowBlog IntroducingContentHealth,anewwaytokeeptheknowledgebaseup-to-date Podcast394:whatifyoucouldinvestinyourfavoritedeveloper? FeaturedonMeta Nowlive:Afullyresponsiveprofile Reducingtheweightofourfooter Linked 3 StartaYouTubevideowhenwebsiteopens 1 Whyisn'tmyYouTubelinkautoplayingwithinaniframeinChrome? 88 YouTube:Howtopresentembedvideowithsoundmuted 60 GettinganEmbeddedYouTubeVideotoAutoPlayandLoop 11 Youtubeiframeapiallow="autoplay"Chrome65 8 youtubeiFrameisblank 2 Playanimationwhencontentgetintoview 3 jQueryplayiframeembeddedYouTubevideoonpageload 0 ForcemanualclickonYoutubeiframeusingJquery 1 Autoclickyoutubeplaybuttononload Seemorelinkedquestions Related 7626 HowdoJavaScriptclosureswork? 8234 HowdoIcheckifanelementishiddeninjQuery? 6837 Removepropertiesfromobjects(JavaScript) 7710 HowdoIredirecttoanotherwebpage? 2617 HowdoIgetaYouTubevideothumbnailfromtheYouTubeAPI? 2261 HowtoprintanumberwithcommasasthousandsseparatorsinJavaScript 2327 HowtocreateanHTMLbuttonthatactslikealink 2194 HowtodecidewhentouseNode.js? 10041 HowcanIremoveaspecificitemfromanarray? 2903 WhydoesmyJavaScriptcodereceivea"No'Access-Control-Allow-Origin'headerispresentontherequestedresource"error,whilePostmandoesnot? HotNetworkQuestions QuestionableCovidprocurementoutsidetheUK TheWitch'sBroom Whatisthepurposeofthisconcertequipment? CanIreplaceabulbwithonewithmorewatt? WhatdothelettersGandDmeanin"TheTrout"bySeanO'Faolain? HowtoCombineanEmissionspectrumintoacolour? SlowdownsinCBMBASICsbetween4.xand7.x? Whatwastherelevanceof'crossingstatelines'intheKyleRittenhousecase? CurlyBracketovermultipleequation HowcanImakean\underbracewithoutabrace? HowcanIworkonDSPusingC/C++? Whydoeswaterboilinbubbles? 4x44-colorGolombsquare TimeComplexityOfSolvingDLogWhengandPareknown WherewasBurÿHaüsnear1663Breitau? HowdoesthisNorton"upgrade"scamwork? WhowouldhavebeentheoptimalpartnerofAliaaccordingtotheBeneGesserit? Doescarbonfibernothaveafatiguelife? WhyisFIPS140-2compliancecontroversial? Questionformattinglikeatable Woulddoublejeopardypreventthisfromhappening? Whydon'tsmallaircraftproducetyresmokewhenlanding,butbigaircraftdo? Runmultiscriptsinafolderwithcron Whatdoes'dosteakandchips'mean? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. default Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?