Incorporating onPause and onResume functionalities into a YouTube video featured on a page built with Ionic 2

I'm encountering a minor problem with a simple demo Android app built in Ionic 2.

Whenever a Youtube video is playing on the Homepage, if the power button is pressed or the phone goes into sleep/lock mode, the Youtube video continues to play. This issue results in Google rejecting the app from being listed in the Play Store because it violates their policy regarding Youtube embeds.

To resolve this issue, I need to implement some code that will pause the video when the state changes and then resume playback when the device wakes up again.

The functionality I believe needs to be added is onPause and onResume, but I'm uncertain about where and how to incorporate the necessary code to make this feature work with the customized Youtube code.

Below are links to the files in a repository and the APK (which is only 3mb). The issue can be observed on a blank Ionic 2 installation by visiting the provided link to the homepage.

Github Repository
APK on Github

Answer №1

Although I would like to add to n00b's comment, I am unable to do so with my current reputation points. It is important to consider noob's answer and give credit where it is due. Please mark n00b as the correct answer since they were the first to respond.

import { DomSanitizer, SafeResourceUrl} from '@angular/platform-browser';

export class page {
    currentVideoSource: SafeResourceUrl;
    constructor(public navCtrl: NavController, private sanitizer: DomSanitizer) {
        this.currentVideoSource = this.sanitizer.bypassSecurityTrustResourceUrl("youtubeurl");
    }

With this setup, you should be able to use something similar to the code snippet below in the iframe:

[src]="currentVideoSource";

Answer №2

To bypass security restrictions in Angular2, consider adding the URL to the DomSanitizer exception list. This is a built-in security measure that safeguards your application from loading potentially harmful URLs.

Click here to learn more about the DomSanitizer class in Angular2.

Answer №3

To avoid the difficulties you're facing, I recommend using the YouTube Video Plugin straight away. You can watch a preview video on how to install it by visiting this link:

NODE

ionic cordova add https://github.com/JonSmart/CordovaYoutubeVideoPlayer

npm install @ionic-native/youtube-video-player

APP.MODULE.TS

import {YoutubeVideoPlayer} from '@ionic-native/youtube-video-player'

Add YoutubeVideoPlayer to the list of providers.

HOME.TS

import {YoutubeVideoPlayer} from '@ionic-native/youtube-video-player'

Under export class:

constructor (private videoPlayer: YoutubeVideoPlayer ) {}

playVideo(video: Video) {
    this.videoPlayer.openVideo(video.videoId)
}

An API Key is necessary for Android. Search for "Youtube Data API Overview".

In config.xml (under allow-intent):

Answer №4

According to information found in this informative blog post,

It has been stated that Apache Cordova event listeners can be utilized.

For IonicFramework, no additional plugin installation is required for Apache Cordova events.

To register an event, it must be done within the $ionicPlatform.ready() method.

Several of these event Listeners include:

resume - Triggered when the application is brought forward from the background by the native platform.

pause - Fired when the application is sent to the background.

online - This fires when the application connects online and the device establishes an Internet connection.

offline - Fired when the application goes offline and the device loses its Internet connection.

To implement in your JS file, include:

angular.module(...).run(function($ionicPlatform){
        $ionicPlatform.ready(function() {
           document.addEventListener("pause", function() {
              //Code to pause the video
           }, false);
     });

For a comprehensive list of supported events, please consult the official Apache Cordova website

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using React to implement MUI autocomplete feature alongside a MUI form

Recently, I have been utilizing a MUI form structured in the following manner: <Box component="form" onSubmit={event => { return handleSubmit(event); }} noValidate sx={{mt: 1}}> <TextField margin="normal" ...

Error: AJAX responseText Mismatch detected

When I make an AJAX call in my code, everything seems to be working correctly. The PHP script responds with "success" when it should, and the response text is indeed "success". However, even though the output appears to be correct, the line if(returnVal == ...

Issue with Empty Date Time Format in Vue2 Date-Picker

In our company, we use vue2-datepicker to manage the starting and ending times of meetings. The dates are stored in "YYYY-MM-DD HH:mm" format on the backend, but we convert them to "DD-MM-YYYY HH:mm" format when retrieving the data in the mounted() hook. T ...

Having trouble transferring files to an unfamiliar directory using Node.js?

const { resolve } = require("path"); const prompt = require('prompt'); const fsPath = require('fs-path'); // Retrieve files from Directory const getFiles = dir => { const stack = [resolve(dir)]; const files = []; whi ...

Using the THIS keyword in JQUERY for functions without an action: a guide

Is there a way to dynamically set the widths of table elements based on their parent's data-attribute value? For example, if a parent has percent="10", I want the child element to have a width of 10%. How can this be accomplished? To illustrate, here ...

What is the best way to incorporate markers into my d3 line chart that includes two separate datasets?

In my JavaScript code, I'm creating a line chart for two datasets using the d3 library with Vue framework integration. Within the HTML code, there are buttons that trigger the updateData function to display the line charts for the respective datasets ...

The call stack reached its maximum size while attempting to send a post request in an Express application

'Error Occurred: RangeError: Maximum Call Stack Size Exceeded' When Making a Post Request in Node.js with Express and body-parser As a beginner in the world of node.js, my journey took a challenging turn while following along with video #30 from ...

Screening strings and arrays based on multiple criteria

My code is below and I am trying to have the bot check for two specific conditions in the user's message. The message must contain "how" plus either "doing" or "bread". It works perfectly when using only "doing" but not when adding the "bread" conditi ...

Using Jquery and CSS to display or conceal table elements depending on viewport width

I am seeking advice for my issue. Here is the code snippet on JSFiddle. I have a list of models and corresponding values that vary across different categories. I have created a simple table to display this data. However, I need to alter the table structur ...

What are some ways I can troubleshoot my contact form?

As someone new to web design, I recently completed my very first site using a combination of HTML, CSS, and a touch of JavaScript. I managed to create a small contact form within the site, but now I'm wondering if there's a way to make it functio ...

What are the steps to extracting JSON data in Node.js?

I am currently utilizing the API's node wrapper provided by MySportsFeeds. You can find more information about it here: https://github.com/MySportsFeeds/mysportsfeeds-node/blob/master/README.md The API call is functioning smoothly and the data is aut ...

Guide on Generating SAS Token for Azure Table Storage in a jQuery Application

I am currently working on a jQuery web application that requires read-only access to an Azure Table Storage, fetching one record at a time by passing in the PartitionKey and RowKey. To simplify my code, I have integrated the Azure Storage JavaScript Client ...

Tips for detecting the end of a scroll view in a list view

I've encountered an issue with my scrollView that allows for infinite scrolling until the banner or container disappears. What I'm aiming for is to restrict scrolling once you reach the last section, like number 3, to prevent the name part from m ...

ngx-datatable detail row failing to expand properly

I am striving to develop an ngx-datatable component that can be utilized universally for consistent styling and functionality. Although most features are working correctly, I'm struggling to understand why the details row isn't expanding as expe ...

Error encountered during Cordova installation: potential path problem - error code ENOENT

After successfully installing Xcode and NodeJS, I encountered an error while trying to install Cordova. The error message indicated that a file was missing (possibly due to an incorrect path). Luciens-MacBook-Pro:~ lucientavano$ npm cache clean Luciens-Ma ...

Showing the Angular UI Router's loading view without loading the controller

There seems to be an issue with my angular app using ui-router. Despite all templates loading and displaying correctly, only the DashboardCtrl controller is being called. This behavior is quite puzzling. var adminPanel = angular.module('adminPanel&ap ...

Ways to align and fix a button within a specific div element

How can I make the button with position: fixed property only visible inside the second div and not remain fixed when scrolling to the first or last div? .one{ height:600px; width: 100%; background-color: re ...

Leverage the power of react-i18next in class-based components by utilizing decorators and Higher Order

Currently, I am working on implementing i18n into my React project that also utilizes Redux, with the assistance of react-i18next. In this particular project, we are using class components alongside decorators. Originally, I intended to experiment with r ...

The OTP submission in Phone Email's phone authentication using Node JS did not result in the reception of the token

I have implemented the “Login with Phone” Button from Phone Email on my Node JS website. The button opens a popup to enter the mobile number and then displays an OTP window after submission. Although I receive the OTP SMS and enter it successfully, I a ...

The issue of why padding left is not functioning correctly in Bootstrap version 5.3.1

</head> <body> <header class="bg-info "> <div class="container"> <div class="row text-white"> <div class="col-md-6 p-3 pl-6 "> ...