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

user input not displayed within md-autocomplete

I'm currently incorporating angular material's autocomplete component into my website. Within the html code, I have the following: <md-autocomplete md-selected-item="selectedItem" md-search-text="searchText" md-items="item in getMatches ...

Mastering the Use of *ngIf with *ngFor: Best Practices for Proper Implementation

Can someone help me rewrite the combination of *ngIF and *ngFor below? I understand that my issue may be similar to others, but please know that this is different. Everything seems to be working fine. The only problem I'm facing is that the color of ...

Obtain the month, day, or year from a timestamp

Can anyone provide guidance on extracting a specific date format (date, month, day, year) from a timestamp? I am interested in implementing this feature within a view using Backbone JS. ...

Please display the Bootstrap Modal first before continuing

Currently, I'm facing a challenge with my JS code as it seems to continue running before displaying my Bootstrap Modal. On this website, users are required to input information and upon pressing the Save button, a function called "passTimeToSpring()" ...

Tap on the div nested within another div

Here is the scenario I am dealing with: <div id="main"> <div id="a"></div> <div id="b"></div> </div> On my website, element B is positioned below element A. How can I attach a click event only to those A elements t ...

Take a sequence of multiple words and combine them into a single string with hyphens in between

I've been working on a WordPress website and I created a JavaScript function that adds a class to the body tag, allowing for different backgrounds based on the category. It works perfectly fine when the category is a single word, but encounters issues ...

What is the best way to send extra parameters to an ajax callback function?

Currently, I am implementing an ajax call in the following manner: util.AjaxCall(url, successCallbackFunction, errorCallbackFunction); function successCallbackFunction(result) { // Result returned from Ajax } Although everything is functioning correc ...

TypeScript compiler not processing recently generated files

While working on a project using TypeScript, I've noticed that the files compile without any issues when using tsc with the watch flag to monitor changes. However, I have run into an issue where when I create a new file, tsc does not automatically det ...

Ways to fetch a JSON object using JavaScript

Currently, I am in the process of creating an HTML5 mobile application and utilizing jQuery to fetch a JSON file from this URL: . Here is the code snippet I used: var url='http://cin.ufpe.br/~rvcam/favours.json'; $.getJSON(url, function(data, s ...

What's the best way to target an input that's appearing as it slides in from the edge of the screen?

My webpage has an element called #cols that is three times wider than the <body>. This element contains three columns, each exactly as wide as the <body>. When a button is clicked, the #cols element slides over by the width of one column while ...

JavaScript's onclick function for clearing dropdown fields will only work once for each specific dropdown field

I have scoured all the related questions and answers on StackOverflow, but none seem to address my specific issue. Here is the HTML code I am using: <select name="search_month" onclick="javascript: $('#categories').val(null);" id="months"> ...

Creating a JSON Response Using PHP API

I created a basic JSON response to test the functionality of an AJAX request on a mobile device. Using a local domain called test.local, I generated a json response. header("Content-Type:application/json; charset=utf-8"); echo json_encode(array('nam ...

Retrieve the output of a function once the function has completed

I'm facing an issue where I need to wait for a function to return a value from my MySQL table before using it as a return for my const ProjektNameIntentHandler. Here is the relevant code snippet: const ProjektNameIntentHandler = { canHandle(handlerIn ...

Retrieve input value in Angular 8 using only the element's ID

Can the value of an input be obtained in Angular 8 with TypeScript if only the element's id is known? ...

Issue with CSS: Dropdown menu is hidden behind carousel while hovering

I'm struggling with adjusting the position of my dropdown list. It keeps hiding behind the carousel (slider). When I set the position of the carousel section to absolute, it causes the navbar to become transparent and the images from the carousel show ...

Issue: Headers cannot be set after they have been sent. This is a problem in node.js

I'm trying to create an application that allows users to execute commands via a URL, but I keep encountering this error message: _http_outgoing.js:346 throw new Error('Can\'t set headers after they are sent.'); ^Error: Can't ...

Verifying in PHP if the request is intended for a JavaScript worker

After doing my research on MDN for the referrer-policy, as well as searching through Google, DuckDuckGo and Stack Overflow, I still find myself stuck on a seemingly simple yet elusive issue. Journey of Data the browser sends a request to the server the ...

SOLVED: NextJS restricts plugins from modifying HTML to avoid unnecessary re-rendering

My current scenario is as follows: I am in the process of developing a website using NextJS (SSR) I have a requirement to load a script that will locate a div element and insert some HTML content (scripts and iframes) within it. The issue at hand: It se ...

Setting multiple values on a form can be accomplished by using the appropriate form fields

When it comes to setting values on fields, I am aware that I can choose between using setValue or patchValue However, I am currently encountering a situation where I need to avoid setting the value on each field individually. Take a look at my f ...

Navigation issue discovered while trying to implement Ionic's collection-repeat feature

As a newcomer to Ionic and Angular.js, I recently downloaded an example of an ionic collection repeat and navigation from http://codepen.io/ionic/pen/mypxez. Initially, the example worked perfectly with just single index.html and index.js files. However, I ...