How to stop video playing in background Nativescript -angular - nativescript

Im using video in my project ,but video is playing in background ,When i move to another component.This problem occurs only in ios ,not in android
Html
<VideoPlayer
src="{{videoUrl}}"
height="300"></VideoPlayer>
angular
index:any
videoUrl :any
ngOnInit() {
this.router.paramMap.subscribe(
(response) =>{
this.index = response.get('id')
this.videoUrl=this.galleryService.getVideoById(this.index)
console.log(response)
}
)
}
This is my code .

Listen to navigatingFrom event on your current Page and call pause() method on the VideoPlayer.
HTML
<VideoPlayer #player
src="{{videoUrl}}"
height="300"></VideoPlayer>
TS
#ViewChild("player") player: ElementRef;
constructor(private page: Page) { }
ngOnInit() {
this.router.paramMap.subscribe(
(response) => {
this.index = response.get('id')
this.videoUrl=this.galleryService.getVideoById(this.index)
console.log(response)
});
this.page.on(Page.navigatingFromEvent, () => {
this.player.nativeElement.pause();
});
}
ngOnDestroy() {
this.page.off(Page.navigatingFromEvent);
}
You may also use Router Events on Angular, but you might have to filter the appropriate route.

Related

calling back-end api (laravel) from getServerSideProps() in next js

I am using next js as a front-end and laravel as a back-end. and i want to call back-end (laravel) api from getServerSideProps() method. as shown below
export async function getServerSideProps(context) {
const response = await Axios.request({
url: 'http://localhost:8000/api/event',
method: 'get',
headers: {
Cookie: context.req.headers.cookie,
},
})
const events = response.events
console.log(response)
return {
props: { events },
}
}
so i have also set the cookie but i am getting response with message unauthenticated like below
I just wanted to say a huge THANK YOU to Riaz Kahn for his answer. After a lot of banging my face against a wall this was the answer. I'm going to post a working example of my getServerSideProps function for anyone arriving here in the future. The getUser({[configObject]}) function is just returning a promise from an axios.get('my-user/route', config) call. This is working properly in a Next 13 app using standard pages functionality (not using experimental app directory).
export const getServerSideProps = async (context: any) => {
const {req, res} = context;
try {
const {data: user} = await getUser({
headers: {...req.headers}
});
return {
props: {
fallback: {user}
}
}
} catch (e) {
res.writeHead(302, {Location: '/login'});
res.end();
}
}

Download link excel in vuejs

In controller laravel: I use box/spout , I save the excel file in a separate folder, and i create a variable that points to the folder where the file is saved, and i return the vuejs view to download that file
$path = '/files/'.$name;
$urlFile = url('/files/'.$name);
var_dump($urlFile);
// Result:
http://localhost.loca/file/data.xlsx
I return view vuejs:
return response()->json($urlFile);
View vuejs :
methods: {
// event button click
clickButton() {
axios
.get("/api/export")
.then((res) => {
console.log(res.data) // http://localhost.loca/file/data.xlsx
// I want to download this link !
})
.catch((error) => {
console.log(error);
});
}
}
Please give me idea download link ? Thanks
Update: I use window.open(res.data) but it doesn't work
Try to create an anchor and click on it programmatically to download the file :
.then((res) => {
console.log(res.data) // http://localhost.loca/file/data.xlsx
//create and append anchor download to body
const downloadAnchor = document.createElement("a");
downloadAnchor.setAttribute("href", "http://localhost.loca/file/data.xlsx");
downloadAnchor.setAttribute("download", "data.xlsx");
document.body.appendChild(downloadAnchor);
downloadAnchor.click();
//remove anchor download
document.body.removeChild(downloadAnchor);
})
If window.open doesn't work you can try this:
function download(url) {
const a = document.createElement('a')
a.href = url
a.download = url.split('/').pop()
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
And then call the download function in your method:
methods: {
// event button click
clickButton() {
axios
.get("/api/export")
.then((res) => {
console.log(res.data) // http://localhost.loca/file/data.xlsx
download(res.data)
})
.catch((error) => {
console.log(error);
});
}
}

How can I do a simple AJAX call to play audio via React / Redux?

I am trying to auto play some audio, and on iOS, it won't autoplay. However, if I wrap it in an AJAX call, it'll fire. So here's what I have:
// run on page load
var audio = document.getElementById('audio');
jQuery.ajax({
url: 'ajax.js',
async: false,
success: function() {
audio.play(); // audio will play in iOS before 4.2.1
}
});
How would I set this up with React / Redux?
Here's a very simple example using fetch (which is supported by most browsers out of the box) and blob object URLs. You could of course also use jQuery's ajax.
It's very similar to your code, but inside the componentDidMount method. The audio element is referenced via React's refs.
class Player extends React.Component {
componentDidMount() {
fetch(this.props.src)
.then(res => res.blob())
.then(blob => {
const { audio } = this.refs;
audio.src = URL.createObjectURL(blob);
audio.play();
});
}
render() {
return <audio ref="audio" controls></audio>;
}
}
ReactDOM.render(
<Player src="https://ia802508.us.archive.org/5/items/testmp3testfile/mpthreetest.mp3" />,
document.getElementById("View")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='View'></div>
🔊❗️
Also, it is usually not recommended to use refs in React, but since we need access to the actual DOM node of the audio player it is a necessary evil.

How to load AJAX in react

Im trying to get my json result into my react code
The code looks like the following
_getComments() {
const commentList = "AJAX JSON GOES HERE"
return commentList.map((comment) => {
return (
<Comment
author={comment.author}
body={comment.body}
avatarUrl={comment.avatarUrl}
key={comment.id} />);
});
}
How do i fetch AJAX into this?
First, to fetch the data using AJAX, you have a few options:
The Fetch API, which will work out of the box in some browsers (you can use a polyfill to get it working in other browsers as well). See this answer for an example implementation.
A library for data fetching (which generally work in all modern browsers). Facebook recommends the following:
superagent
reqwest
react-ajax
axios
request
Next, you need to use it somewhere in your React component. Where and how you do this will depend on your specific application and component, but generally I think there's two scenarios to consider:
Fetching initial data (e.g. a list of users).
Fetching data in response to some user interaction (e.g. clicking a
button to add more users).
Fetching initial data should be done in the life-cycle method componentDidMount(). From the React Docs:
var UserGist = React.createClass({
getInitialState: function() {
return {
username: '',
lastGistUrl: ''
};
},
componentDidMount: function() {
this.serverRequest = $.get(this.props.source, function (result) {
var lastGist = result[0];
this.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
});
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
<div>
{this.state.username}'s last gist is
<a href={this.state.lastGistUrl}>here</a>.
</div>
);
}
});
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
mountNode
);
Here they use jQuery to fetch the data. While that works just fine, it's probably not a good idea to use such a big library (in terms of size) to perform such a small task.
Fetching data in response to e.g. an action can be done like this:
var UserGist = React.createClass({
getInitialState: function() {
return {
users: []
};
},
componentWillUnmount: function() {
this.serverRequest && this.serverRequest.abort();
},
fetchNewUser: function () {
this.serverRequest = $.get(this.props.source, function (result) {
var lastGist = result[0];
var users = this.state.users
users.push(lastGist.owner.login)
this.setState({ users });
}.bind(this));
},
render: function() {
return (
<div>
{this.state.users.map(user => <div>{user}</div>)}
<button onClick={this.fetchNewUser}>Get new user</button>
</div>
);
}
});
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
mountNode
);
Lets take a look on the fetch API : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Lets say we want to fetch a simple list into our component.
export default MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
lst: []
};
this.fetchData = this.fetchData.bind(this);
}
fetchData() {
fetch('url')
.then((res) => {
return res.json();
})
.then((res) => {
this.setState({ lst: res });
});
}
}
We are fetching the data from the server, and we get the result from the service, we convert is to json, and then we set the result which will be the array in the state.
You can use jQuery.get or jQuery.ajax in componentDidMount:
import React from 'react';
export default React.createClass({
...
componentDidMount() {
$.get('your/url/here').done((loadedData) => {
this.setState({data: loadedData});
});
...
}
First I'd like to use fetchAPI now install of ajax like zepto's ajax,the render of reactjs is asyn,you can init a state in the constructor,then change the state by the data from the result of fetch.

Using Kango API from iFrame

Using Kango, I have added an iFrame to a page. This iFrame points to an internal resource. I want this iFrame to be able to communicate with the background script. I would love to actually get the Kango API accessable from the iFrame, but if this is not possible I wonder how I might target this iFrame with a content script.
From your application that is inside the iFrame you can do:
top.window.postMessage({ type: 'EVENT', data: {} }, "*");
Then inside your Kango extension HTML link a JS file that has:
KangoAPI.onReady(function () {
window.addEventListener('message', function (event) {
console.log('host.js -> message', event);
kango.dispatchMessage('MessageToWindow', event);
});
document.body.onload = function () {
try {
document.getElementById('iFrameID').src = 'URL';
} catch (ex) {
throw ex;
}
}
});
Then inside the background.js
kango.addMessageListener('MessageToWindow', function (event) {
console.log('background.js -> MessageToWindow', event);
kango.browser.tabs.getCurrent(function (tab) {
console.log('background.js -> TAB', tab || 'NONE');
console.log('background.js -> TYPE', event.data.data.type || 'NONE');
console.log('background.js -> DATA', event.data.data.data || 'NONE');
tab.dispatchMessage(event.data.data.type, event.data.data.data);
});
});
Lastly, inside the content.js
kango.addMessageListener('EVENT', function(event) {
kango.console.log('got event');
});
Seems like a lot, but this was the only way that I could get it to work. Hope that helps!

Resources