I cannot find anthing in Twilio Docs about event fired up when called user answers the call. Connection.accept(handler) is fired up only on called user browser when he anwsers. Im doing connection between two browsers in Aurelia.js and I want to start the timer on moment when call is answered, but none of the events described in docs seems to fire up when called user answers. This is my client code.
setupTwilio() {
this.http.get("twilio/client/create").then(response => {
this.twilioData = JSON.parse(response.response);
Twilio.Device.setup(this.twilioData.token);
Twilio.Device.offline((device)=>{
Twilio.Device.destroy();
this.setupTwilio();
});
Twilio.Device.ready((device) => {
console.log("Ready");
});
Twilio.Device.error((error) => {
console.log("Error: " + error.message);
});
Twilio.Device.connect((conn) => {
this.call.startedAt = moment().unix();
});
Twilio.Device.disconnect((conn) => {
this.rejectCall();
});
Twilio.Device.cancel((conn) => {
this.rejectCall();
});
Twilio.Device.incoming((conn) => {
var userId = conn.parameters.From.split(":").pop().substring(4);
this.http.get('users/' + userId).then((response) => {
this.call.user = JSON.parse(response.response);
$('#incomingCall').modal({backdrop: 'static', keyboard: false});
}).catch(error => {
this.notification.error("Error fetching user");
});
});
});
}
Take a look at this article. https://www.twilio.com/blog/2015/05/introducing-call-progress-events-flexibly-track-and-control-your-outbound-calls.html It explains about call progress events: Initiated, Ringing, Answered, Completed.
Related
First of all, I have to say this is my first question on stack ;)
I am trying to implement a reading via NFC on my test web, but i dunno why, the ndefReader doesn't works on startup, i have to press any field on the web to get it loaded (or asked for permission).
BUT, if i wrote some alerts to check why it doen't reach the function on startup, it works!!! (of course, it show alerts before). I don't know if when I accept the alert, I am interacting with the web and that's why it works, but anyways, I dunno why this happens (I need to click anywhere before starting).
function iniciar() {
document.getElementById("input1").focus();
//alert("test before"); <--- IF i remove this, it doesnt works
document.getElementById("input1").addEventListener("blur", async () => {
try{
const ndef = new NDEFReader();
alert("before wait");
await ndef.scan();
alert("after wait");
ndef.addEventListener("readingerror", () => {
alert("Argh! Cannot read data from the NFC tag. Try another one?");
});
ndef.addEventListener("reading", ({ message, serialNumber }) => {
alert(`> Serial Number: ${serialNumber}`);
alert(`> Records: (${message.records.length})`);
});
} catch (error) {
alert("Argh! " + error);
}
},false);
To scan and write to NFC tags, you must first request the "nfc" permission while handling a user gesture (e.g a button click, or in your case the "alert" call). Once handled, the NDEFReader scan() and write() methods trigger a user prompt, if access was not previously granted.
Check out https://web.dev/nfc/#security-and-permissions to learn more.
Hopefully https://googlechrome.github.io/samples/web-nfc/ samples should help you as well.
scanButton.addEventListener("click", async () => {
console.log("User clicked scan button");
try {
const ndef = new NDEFReader();
await ndef.scan();
console.log("> Scan started");
ndef.addEventListener("readingerror", () => {
console.log("Argh! Cannot read data from the NFC tag. Try another one?");
});
ndef.addEventListener("reading", ({ message, serialNumber }) => {
console.log(`> Serial Number: ${serialNumber}`);
console.log(`> Records: (${message.records.length})`);
});
} catch (error) {
console.log("Argh! " + error);
}
});
I'm trying to perform async operation right before browser redirects user to http://example.com on click.
So, after the ajax call I'm clicking currentTarget again to redirect but it doesn't work.
<a class="notic_click" href="http://example.com">Button</a>
<a class="notic_click" href="http://example.com">Button</a>
$(".notic_click").on("click", function(e, options) {
options = options || {};
// if it hasn't been clicked already
// run this
if( !options.hasClicked ) {
e.preventDefault();
const self = this;
// some other code
$.get("http://example.com/hello")
.always(function() {
$(self).trigger("click", {hasClicked: true});
});
} else {
// I got here, that means e.preventDefault didn't get called and it should redirect
console.log("should redirect but not redirecting");
}
});
I tried $(self).off() right before the trigger, but to no avail.
I have already tried this:
window.location.assign(e.target.href);
and this works. But I'm curious as to what is causing the above not to work.
Browser: Mozilla Firefox (78.0.2)
try this out:
$(".notic_click").on("click", function(e) {
if( e.isTrusted) {
e.preventDefault();
const self = this;
// some other code
$.get("http://example.com/hello")
.always(function() {
$(self).click();
});
} else {
// I got here, that means e.preventDefault didn't get called and it should redirect
console.log("should redirect but not redirecting");
}
});
You can read more about is trusted here: https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted
Try it with this code piece. You seem to have a logic problem in your code. Since you prevent the default, you should "return" to the default behaviour:
<a class="notic_click" href="http://example.com">Button</a>
<a class="notic_click" href="http://example.com">Button</a>
<script>
$(".notic_click").on("click", async function (e, options) {
options = options || {};
e.preventDefault();
console.log('do task here');
await new Promise(resolve => setTimeout(resolve, 3000));
console.log('timeout end');
await new Promise(resolve => setTimeout(resolve, 3000));
window.location = this.href;
});
</script>
Your code appears to work fine in isolation. That being said, a better approach would be to always call preventDefault() to stop the page redirection and then make your async AJAX request. When that request completes you can then use window.location.assign() to redirect the user.
$(".notic_click").on("click", e => {
e.preventDefault();
// I'd suggest putting a loading spinner in the UI here to make it clear
// to the user that their request is in process.
$.get("http://example.com/hello").always(() => {
window.location.assign(e.target.href);
});
});
i have troubles detecting a closing window after the build is done.
const newWindow = window.open(url, '_blank', options);
newWindow.onbeforeunload = () => null;
newWindow.addEventListener('beforeunload', (evt: BeforeUnloadEvent) =>
{
console.log(evt)
}
);
it works great until i do the build, there the beforeunload event does not get triggered. i also tried placing a host listener in the new window's component:
#HostListener('window:beforeunload', [ '$event' ])
beforeUnloadHander(event: BeforeUnloadEvent): void {
debugger;
}
but the same problem here. after the build is done, we don't arrive at the debugger anymore
anybody any idea what i am doing wrong? thanks for your help!
Edit Workaround
const heartBeatNewWindow = setInterval(() => {
if (newWindow.closed) {
this.canvasSettings.displayInNewWindow = false;
clearTimeout(heartBeatNewWindow);
}
}, 1500);
I had to do something similar and my approach was the following:
I created a generic catch from close event windows in the constructor of my service, them call method what handle this event. Inside this method I validate the origin of this event is the correct to execute the logic I needed. Look this example:
Inside the constructor:
if(window.addEventListener){
window.addEventListener("message", this.authService.handleMessage.bind(this), false);
}else{
(<any>window).attachEvent('onmessage', this.authService.handleMessage.bind(this));
}
And my method to handle that event:
handleMessage(event: Event) {
event.preventDefault();
const message = event as MessageEvent;
// Only trust messages from the below origin.
//
if ((message.origin !== environment.BASE_URL)) return;
const result = JSON.parse(message.data);
//Add your logic here
I Hope be helpfull.
I am trying to create a custom tracker for downloads in an electron app. The functionality I desire is to allow there to be a tracker which is created and maintained near the position where download link is clicked. In order to do this, I want to be able to pass the reference to the item which triggered this download.
mainWindow.webContents.session.on('will-download', (event, item, webContents) => {
item.on('updated', (event, state) => {
if (state === 'interrupted') {
console.log('Download is interrupted but can be resumed');
} else if (state === 'progressing') {
if(item.isPaused()) {
console.log('Download is paused');
} else {
console.log(`Received bytes: ${item.getReceivedBytes()}`);
}
}
})
item.once('done', (event, state) => {
if(state === 'completed') {
console.log('Download successful');
} else {
console.log(`Download Failed: ${state}`);
}
})
});
How do I make this happen? It seems that 'will-download' triggers whenever a GET request to a file is made. How do I add arguments to this just before it is clicked? Is this information somehow retrievable from event/webContents?
Sorry if this is obvious, I am a complete noob at web-app development.
Thanks!
After quite some time, I found a better way to accomplish what I was trying to do, using electron-download-manager. I used a seperate ipc event on click, which passed the required arguments, and used electron-download-manager on main to use these arguments to create a 'monitor' channel for the specific download.
Hope this helps someone. Still curious to know whether it is possible to somehow 'overload' the will-download event with extra arguments though.
At the momement I don't know a way to override electrons internal events, but if you have access to all download links, then you can attach a '#' with a custom value to you'r links. This way you can make them uniq and reidentify a link. The pound is a good way, in my point of view, because it has only a special meaning on client and not on server site. I would suggest the following:
<a href="http://ipv4.download.thinkbroadband.com/50MB.zip#test" data-progress="#progress-zipfile" download>download</a> <span id="progress-zipfile">0</span>
Then you can send an event from the Main-Process back to the Renderer-Process like this (example in coffee script):
win.webContents.session.on 'will-download', (event, item, webContents) ->
[url, hash, rest...] = item.getURL().split /#/
file = {url: url, id: hash}
webContents.send 'download-started', { file: file, totalBytes: item.getTotalBytes() }
item.setSavePath('/tmp/download.zip')
item.on 'updated', (event, state) ->
webContents.send 'download-updated', {
file: file,
receivedBytes: item.getReceivedBytes(),
totalBytes: item.getTotalBytes(),
state: state
}
if (state == 'interrupted')
console.log('Download is interrupted but can be resumed')
else if (state == 'progressing')
if (item.isPaused())
console.log('Download is paused')
else
console.log("Received bytes: #{item.getReceivedBytes()}")
item.once 'done', (event, state) ->
if (state == 'completed')
console.log('Download successfully')
else
console.log("Download failed: #{state}")
webContents.send 'download-completed', { file: file, receivedBytes: item.getReceivedBytes(), state: state }
Within your Renderer-Process you can act on the events like this:
<script>
const {ipcRenderer} = require('electron');
const updateProgress = function(url, percent){
let progress = 0;
let anchor = document.querySelector('a[href="' + url + '"]');
let idProgressBar = anchor.dataset.progress;
let progressSpan = document.querySelector(idProgressBar);
progressSpan.textContent=percent.toString() + " %";
};
ipcRenderer.on('download-updated', (event, arg) => {
let file = arg.file;
if (arg.totalBytes && arg.totalBytes > 0){
progress = Math.round(arg.receivedBytes * 100.0 / arg.totalBytes);
} else {
progress = 0;
}
updateProgress(file.url + '#'+ file.id, progress);
});
ipcRenderer.on('download-completed', (event, arg) => {
let file = arg.file;
let progress = 100;
if (arg.state !== 'completed'){
progress = arg.state;
}
updateProgress(file.url + '#'+ file.id, progress);
});
I am using twilio API to implement screen sharing in an emberjs app, I am successfully able to share the screen and also toggle on stopping it. Here is my code ->
this.get('detectRtc').isChromeExtensionAvailable(available => {
if (available) {
const { twilioParticipant } = this.get('participant')
if (this.get('stream') && this.get('stream').active) {
this.get('streamTrack').stop()
this.get('userMedia.mediaStream')
.removeTrack(this.get('streamTrack'))
this.set('isEnabled', false)
twilioParticipant.removeTrack(this.get('streamTrack'))
} else {
this.get('detectRtc').getSourceId(sourceId => {
// "cancel" button is clicked
if (sourceId !== 'PermissionDeniedError') {
// "share" button is clicked extension returns sourceId
this.get('userMedia')
.getScreen(sourceId)
.then(mediaStream => {
this.set('isEnabled', true)
this.set('stream', mediaStream)
this.set('streamTrack', mediaStream.getVideoTracks()[0])
twilioParticipant.addTrack(mediaStream.getVideoTracks()[0])
})
.catch(() => { /* do nothing, but return something */ })
}
})
}
} else {
this.get('flash').status(
'base',
this.get('intl').t('chromeExtension.install'),
{
icon: 'alert-circle',
push: true
}
)
// TODO Show the system popup to install chrome extension from web store
// !!chrome.webstore &&
// !!chrome.webstore.install &&
// chrome.webstore.install(this.webStoreUrl)
}
})
The issue I'm facing is with the stop sharing button which is at the bottom of the app as seen in screenshot below
I need a way to listen to an event handler and execute the some code after clicking on the stop sharing screen button, I know there is an onended event Handler which is mentioned in the MediaStreamTrack docs, but I don't know how to use it, any help will be highly appreciated.
https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack
The "stop sharing" button will trigger the MediaStreamTracks 'ended' event. Try this:
mediaStream.getVideoTracks()[0].addEventListener('ended', () => console.log('screensharing has ended'))
for some reason, #philipp answer is not working for me and I found this quite helpful
https://github.com/webrtc/samples/blob/gh-pages/src/content/getusermedia/getdisplaymedia/js/main.js#L88
this.get('stream').addEventListener('inactive', e => {
console.log('Capture stream inactive - stop recording!');
});