How to Resolve YouTube Video Playing Issue in Background After Navigate to Other Page

We can play a YouTube video on a browser or app using iframe but sometimes after navigating to another page, the video is still playing in the background. Many developers having trouble with the video still running in the background. So, here I will solve this issue using the ionic life cycle and some codes.

HTML content:



Here, [attr.src]="video.video_link | urlsanitizer"  video.video_link is youtube video link and urlsanitizer is a pipe. Here I will show you in detail step by step.

 

Step 1: Use an id in an iframe like id=”video” then our full HTML code is

Here is the below code:



Step 2: Call ionViewWillLeave(){} in your ts page

Step 3: var videos = document.querySelectorAll('iframe, video'); and console it.

Here iframe is a tag name and video is an id

Step 4: Use this function

Array.prototype.forEach.call(videos, function (video) {

console.log(video)

});

Step 5:

if (video.tagName.toLowerCase() === 'video') {

 

video.pause();

} else {

var src = video.src;

 

video.src = src;

}

So, here is the full code. Please use this code in your ts file


ionViewWillLeave() {

var videos = document.querySelectorAll('iframe, video');

Array.prototype.forEach.call(videos, function (video) {

if (video.tagName.toLowerCase() === 'video') {

video.pause();

} else {

var src = video.src;


video.src = src;

}

});

}

Conclusion:

If face the problem after leaving the current page YouTube video still playing, then you can use this code. Hope you have found your solution. This is very important for Ionic app development. Please share your review in the comment section.

Comment Box

We Serve clients globally in diverse industries

Stay Upto Date With Our Newsletter.