Code to Start and Stop a broadcasting script on a schedule - html

I am somewhat new to coding.
I work for a sports complex and I have set up live streaming.
Currently I have to manually go into the streaming platform and click "start broadcasting" and "stop broadcasting" when I want those things to happen.
I am wondering if I can add code to the HTML to do these functions automatically on a scheduled timer I specify?
Thanks,
Jade

Your code is not specific, but I am going to assume you have javascript functions defined somewhere that can start and stop broadcasting. Something like this:
function startBroadcasting() {
// do whatever it takes to start broadcasting
}
function stopBroadcasting() {
// do whatever it takes to stop broadcasting
}
What you need then, is to call, in a script tag at the bottom of the body, something like this:
var running = false;
function myScheduler() {
var now = new Date();
var dow = now.getDay();
var hr = now.getHours();
var min = now.getMinutes();
var sec = now.getSeconds();
if (dow === 6 && hr === 7 && min === 0 && !running) {
setTimeout(startBroadcasting, 0);
}
if (dow === 9 && hr === 21 && min === 0 && running) {
setTimeout(stopBroadcasting, 0);
}
}
setInterval(myScheduler, 1000);

The embedded code for the player on the website is below. Where and how would I implement the schedule into this?
<!--SVP embed code begin-->
<div id="svp_player5zen1ooango4" style="width:720px;height:405px;position:relative;">
<a class="svp_embed_link" style="color:#000;cursor:default;" href="http://www.streamingvideoprovider.com/how_to_create_tv_channel.html" title="create tv channel" >create tv channel</a>
</div>
<script language="javascript" type="text/javascript" src="http://play.streamingvideoprovider.com/js/dplayer.js"></script>
<script language="javascript">
<!--
var vars = {clip_id:"5zen1ooango4",transparent:"false",pause:"1",repeat:"",bg_color:"#FFFFFF",fs_mode:"2",no_controls:"",start_img:"1",start_volume:"100",close_button:"",brand_new_window:"1",auto_hide:"1",stretch_video:"",player_align:"NONE",offset_x:"",offset_y:"",player_color_ratio:0.6,skinAlpha:"80",colorBase:"#202020",colorIcon:"#FFFFFF",colorHighlight:"#fcad37",direct:"true",is_responsive:"false",viewers_limit:0,cc_position:"bottom",cc_positionOffset:70,cc_multiplier:0.03,cc_textColor:"#ffffff",cc_textOutlineColor:"#000000",cc_bkgColor:"#000000",cc_bkgAlpha:0.7};
var svp_player = new SVPDynamicPlayer("svp_player5zen1ooango4", "", "720", "405", {use_div:"svp_player5zen1ooango4",skin:"3"}, vars);
svp_player.execute();
//-->
</script>
<noscript>Your browser does not support JavaScript! JavaScript is needed to display this video player.</noscript>
<!--SVP embed code end-->

As you can see form their page StreamingVideoProvider has an API to control your broadcast, which is explained here.
First of all you need to get an access token by requesting the svp_auth_get_token service.
After that you can start/stop your broadcast by calling svp_start_broadcast/svp_stop_broadcast where you need to pass your token and the video ID (in your case it's 5zen1ooango4).
At the top of the API docs there is an download link for some example code which may help you.

Related

Update Google Calendar UI after changing visability setting via Workspace Add-On

I have a very basic Google Workspace Add-on that uses the CalendarApp class to toggle the visabilty of a calendar’s events when a button is pressed, using the setSelected() method
The visabilty toggling works, but the change in only reflected in the UI when the page is refreshed. Toggling the checkbox manually in the UI reflects the change immediately without needing to refresh the page.
Is there a method to replicate this immediate update behaviour via my Workspace Add-On?
A mwe is below.
function onDefaultHomePageOpen() {
// create button
var action = CardService.newAction().setFunctionName('toggleCalVis')
var button = CardService.newTextButton()
.setText("TOGGLE CAL VIS")
.setOnClickAction(action)
.setTextButtonStyle(CardService.TextButtonStyle.FILLED)
var buttonSet = CardService.newButtonSet().addButton(button)
// create CardSection
var section = CardService.newCardSection()
.addWidget(buttonSet)
// create card
var card = CardService.newCardBuilder().addSection(section)
// call CardBuilder.call() and return card
return card.build()
}
function toggleCalVis() {
// fetch calendar with UI name "foo"
var calendarName = "foo"
var calendarsByName = CalendarApp.getCalendarsByName(calendarName)
var namedCalendar = calendarsByName[0]
// Toggle calendar visabilty in the UI
if (namedCalendar.isSelected()) {
namedCalendar.setSelected(false)
}
else {
namedCalendar.setSelected(true)
}
}
In short: Create a chrome extension
(2021-sep-2)Reason: The setSelected() method changes ONLY the data on server. To apply the effect of it, you need to refresh the page. But Google Workspace Extension "for security reason" does not allow GAS to do that. However in an Chrome Extension you can unselect the checkbox of visibility by plain JS. (the class name of the left list is encoded but stable for me.) I have some code for Chrome Extension to select the nodes although I didn't worked it out(see last part).
(2021-jul-25)Worse case: Default calendars won't be selected by getAllCalendars(). I just tried the same thing as you mentioned, and the outcome is worse. I wanted to hide all calendars, and I am still pretty sure the code is correct, since I can see the calendar names in the console.
const allCals = CalendarApp.getAllCalendars()
allCals.forEach(cal => {console.log(`unselected ${cal.setSelected(false).getName()}`)})
Yet, the principle calendar, reminder calendar, and task calendar are not in the console.
And google apps script dev should ask themselves: WHY DO PEOPLE USE Calendar.setSelected()? We don't want to hide the calendar on the next run.
In the official document, none of these two behaviour is mentioned.
TL;DR part (My reason for not using GAS)
GAS(google-apps-script) has less functionality. For what I see, google is trying to build their own eco-system, but everything achievable in GAS is also available via javascript. I can even use typescript and do whatever I want by creating an extension.
GAS is NOT easy to learn. The learning was also painful, I spent 4 hours to build the first sample card, and I can interact correctly with the opened event after 9 hours. The documentation is far from finished.
GAS is poorly supported. The native web-based code editor (https://script.google.com/) is not build for coding real apps, it loses the version control freedom in new interface. And does not support cross-file search. Instead of import, codes run from top to bottom in the list, which you need to find that by yourself. (pass along no extension, no prettier, I can tolerate these)
In comparison with other online JS code editors, like codepen / code sandbox / etcetera it does so less function. Moreover, VSCode also has a online version now(github codespaces).
I hope my 13 hours in GAS are not totally wasted. As least whoever read this can just avoid suffering the same painful test.
Here's the code(typescript) for disable all the checks in Chrome.
TRACKER_CAL_ID_ENCODED is the calendar ID of which I don't want to uncheck. Since it is not the major part of this question, it is not very carefully commented.
(line update: 2022-jan-31) Aware that the mutationsList.length >= 3 is not accurate, I cannot see how mutationsList.length works.
Extension:
getSelectCalendarNode()
.then(unSelectCalendars)
function getSelectCalendarNode() {
return new Promise((resolve) => {
document.onreadystatechange = function () {
if (document.readyState == "complete") {
const leftSidebarNode = document.querySelector(
"div.QQYuzf[jsname=QA0Szd]"
)!;
new MutationObserver((mutationsList, observer) => {
for (const mutation of mutationsList) {
if (mutation.target) {
let _selectCalendarNode = document.querySelector("#dws12b.R16x0");
// customized calendars will start loading on 3th+ step, hence 3, but when will they stop loading? I didn't work this out
if (mutationsList.length >= 3) {
// The current best workaround I saw is setTimeout after loading event... There's no event of loading complete.
setTimeout(() => {
observer.disconnect();
resolve(_selectCalendarNode);
}, 1000);
}
}
}
}).observe(leftSidebarNode, { childList: true, subtree: true });
}
};
});
}
function unSelectCalendars(selectCalendarNode: unknown) {
const selcar = selectCalendarNode as HTMLDivElement;
const calwrappers = selcar.firstChild!.childNodes; // .XXcuqd
for (const calrow of calwrappers) {
const calLabel = calrow.firstChild!.firstChild as HTMLLabelElement;
const calSelectWrap = calLabel.firstChild!;
const calSelcted =
(calSelectWrap.firstChild!.firstChild! as HTMLDivElement).getAttribute(
"aria-checked"
) == "true"
? true
: false;
// const calNameSpan = calSelectWrap.nextSibling!
// .firstChild! as HTMLSpanElement;
// const calName = calNameSpan.innerText;
const encodedCalID = calLabel.getAttribute("data-id")!; // const decodedCalID = atob(encodedCalID);
if ((encodedCalID === TRACKER_CAL_ID_ENCODED) !== calSelcted) {
//XOR
calLabel.click();
}
}
console.log(selectCalendarNode);
return;
}
There is no way to make a webpage refresh with Google Apps Script
Possible workarounds:
From the sidebar, provide users a link that redirects them to the Calendar UI webpage (thus a new, refreshed version of it will be opened)
Install a Goole Chrome extension that refreshes the tab in specified intervals

How to hide the source code of a HTML page

I created an HTML page and now would like to hide the source code and encrypt it.
How can I do that?
You can disable the right click, but that's a bad idea because expert minds can read anything from your page.
You cannot totally hide the page source - this is not possible. Nothing is secure enough on the Internet.
In any case, you can encrypt it and set a password.
You can utilise this link - it will encrypt your HTML page with a password.
First up, disable the right click, by writing out this script, right after the tag.
<SCRIPT language=JavaScript>
<!-- http://www.spacegun.co.uk -->
var message = "function disabled";
function rtclickcheck(keyp){ if (navigator.appName == "Netscape" && keyp.which == 3){ alert(message); return false; }
if (navigator.appVersion.indexOf("MSIE") != -1 && event.button == 2) { alert(message); return false; } }
document.onmousedown = rtclickcheck;
</SCRIPT>
Then, encrypt all of it, in this website, called 'AES encryption'.
Link - http://aesencryption.net/
You need to set a password to decrypt it ....you choose the password.
After encrypting it, you can just write a basic HTML page just putting into the <head> tag once again the script to disable the right click, into the <body> tag you code and hide everything just writing at top of the page <html hidden>.
Example
<!DOCTYPE html>
<html hidden>
<head>
<SCRIPT language=JavaScript>
<!-- http://www.spacegun.co.uk -->
var message = "function disabled";
function rtclickcheck(keyp){ if (navigator.appName == "Netscape" && keyp.which == 3){ alert(message); return false; }
if (navigator.appVersion.indexOf("MSIE") != -1 && event.button == 2) { alert(message); return false; } }
document.onmousedown = rtclickcheck;
</SCRIPT>
</head>
<body>
--here, you put the encrypted code from the link above--
</body>
</html>
Where it is written var message = "function disabled"; you can write for example something like 'This page cannot be viewed' or something which will annoy most of the users and will just leave. ['This page is unavailable' and so on ....].
Finally, you will see a blank page with a message coming up as soon as you right click the page. The message will be something like 'This page is no longer active'.
Example
<SCRIPT language=JavaScript>
<!-- http://www.spacegun.co.uk -->
var message = "**This page is no longer active**";
function rtclickcheck(keyp){ if (navigator.appName == "Netscape" && keyp.which == 3){ alert(message); return false; }
if (navigator.appVersion.indexOf("MSIE") != -1 && event.button == 2) { alert(message); return false; } }
document.onmousedown = rtclickcheck;
</SCRIPT>
I do know that one can remove the <html hidden> or the Javascript script with some add-ons such as Firebug but anyway you will need to decrypt the code with a password in order to see the real page.
Expert users might view the source code with a Brute Force attack, I think.
So, nothing is safe.
I found out an application that you need to instal on your computer.
There is a feature in the Enterprise version but you must pay to get it. This feature is a tool which encrypt your HTML page creating an ultra-strong password encryption for HTML files using up to 384 bit keys for encryption [the link I wrote above uses up to 256 bit keys for encryption].
I have never tried it out, though, because it is not for free.
Anyway, the link of the software 'HTML Guardian' - http://www.protware.com/default.htm
For the feature about the encryption, merely click on 'Ultra-Strong HTML password protection' in the page.
You cannot hide the source code, but you can add some difficulties to see your source code by following way
1. Disable right-click:
<body oncontextmenu="return false">
2.Disable ctrl, u, F12 keys:
<script type="text/javascript">
function mousehandler(e) {
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if ((eventbutton == 2) || (eventbutton == 3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;
function disableCtrlKeyCombination(e) {
var forbiddenKeys = new Array("a", "s", "c", "x","u");
var key;
var isCtrl;
if (window.event) {
key = window.event.keyCode;
//IE
if (window.event.ctrlKey)
isCtrl = true;
else
isCtrl = false;
}
else {
key = e.which;
//firefox
if (e.ctrlKey)
isCtrl = true;
else
isCtrl = false;
}
if (isCtrl) {
for (i = 0; i < forbiddenKeys.length; i++) {
//case-insensitive comparation
if (forbiddenKeys[i].toLowerCase() == String.fromCharCode(key).toLowerCase()) {
return false;
}
}
}
return true;
}
</script>
3. Add to lots of white spaces to before you staring your codes
it may fool someone
There isn't really anyway to do it that would stop a someone who is sophisticated.
There isn't really a way to do that. Perhaps the only thing you could do is to disable the right click feature via JavaScript, but still that wouldn't stop a user who's experienced enough to copy it. However, check this out.
for php, separate the code you don't want seen from the rest of your code with:
<?php
for($i=0;$i<1000000;$i++){
echo "\n";
}
?>
<some html="what you want to hide">
<?php
for($i=0;$i<1000000;$i++){
echo "\n";
}
?>
This will effectively kill the view source aspect (at least for a few minutes)
if it is a viewing source, he will not wait for the results.
Also, this does not seem to slow the page load
I know, it's a little late, but I guess you are looking for something called obfuscation. For Javascript files for example are many obfuscation tools available that you can use for the build process of your webpage. The code is transferred in an unreadable format. Some VPS providers are offers plugins that run during the build process and do that job for you.
As many have said, there's no real way to hide source code. There's been some good suggestions but I haven't seen this. This will encode it so nobody can read it, and it will 100% work for HTML. Only thing is anyone smarter than a light bulb will be able to decode it the same way it was encoded. You also cannot encode JavaScript or PHP; HTML only. developers.evrsoft.com offers a free encoder. But again, it can be decoded as quickly as it was encoded.
It'll look like this:
<h1>This will be encoded</h1>
Will be:
<script>
<!--
document.write(unescape("%3Ch1%3EThis%20will%20be%20encoded%3C/h1%3E"));
//-->
</script>
Again, don't encode PHP or JS.

Creating a basic chatbar?

Below is old; look at the updated text at the bottom.
So my friends and I use google docs to communicate while in school, and we setup the challenge to create a working and "efficient" chat bar to communicate with better results. I've been around JavaScript for quite some time, but have never fooled around with Google Apps Script before. We are using the document app for our chats; the code I came up with is as below, but I have a few problems with it:
Errors when a user closes it, then goes to Chat -> Open Chat in the toolbar to re-open, saying, "Error encountered: An unexpected error occurred"; does not specify a line or reason
Needs a hidden element somewhere in the document which can allow users to see what others have typed, but that they can't edit without using the chat box (would add event listener to update chat box when text is ammended)
//Main function, ran when the document first opens.
function onOpen() {
var app = UiApp.createApplication(); //Create a Ui App to use for the chat bar
if(getCurrentUser()=="dev1"||getCurrentUser()=="dev2"){ //user-Id's hidden for privacy
DocumentApp.getUi().createMenu('Chat')
.addItem('AutoColor', 'autoColor')
.addItem('Open Chat', 'createChatBox')
.addItem('Elements', 'displayElements') //Hidden as it is not important for regular use
.addItem('MyID', 'showUser')
.addToUi();
}else{
DocumentApp.getUi().createMenu('Chat')
.addItem('AutoColor', 'autoColor')
.addItem('Open Chat', 'createChatBox')
.addToUi();
}
}
//Creates and returns the chats GUI
function createChatBox(){
var app = UiApp.getActiveApplication()
app.setTitle("Chat Bar (not yet working)");
var vPanel = app.createVerticalPanel().setId('chatPanel').setWidth('100%');
var textArea = app.createTextArea().setId('chatBox').setName('chatBox').setReadOnly(true).setText('').setSize('250px', '450px'); //Read only so they can not edit the text, even if it won't affect overall chat
var textBox = app.createTextBox().setId('messageBox').setName('messageBox').setText('Words');
var chatHandler = app.createServerHandler("sayChat").addCallbackElement(textArea).addCallbackElement(textBox);
var chatButton = app.createButton().setId("sayButton").setText("Say!").addMouseUpHandler(chatHandler);
vPanel.add(textArea);
vPanel.add(textBox);
vPanel.add(chatButton);
app.add(vPanel);
DocumentApp.getUi().showSidebar(app);
return app;
}
//The event handler for when the "Say!" (post) button is pressed. Is probably where the conflict stems from.
function sayChat(eventInfo){
var app = UiApp.getActiveApplication();
var parameter = eventInfo.parameter;
app.getElementById("chatBox").setText(parameter.chatBox+"["+getCurrentUser()+"]: "+parameter.messageBox);
app.getElementById("messageBox").setText("");
return app;
}
//A debug function and a function to tell you the unique part of your email (useless, really)
function showUser(){
DocumentApp.getUi().alert("Your userId is: "+getCurrentUser());
}
//Returns the unique part of a person's email; if their email is "magicuser#gmail.com", it returns "magicuser"
function getCurrentUser(){
var email = Session.getActiveUser().getEmail();
return email.substring(0,email.indexOf("#"));
}
//The Auto-color and displayElements methods are hidden as they contain other user-info. They both work as intended and are not part of the issue.
I do not need someone to rewrite the code (although that'd be greatly appreciated!), but instead point out what I'm doing wrong or suggest something to change/add.
Last, before you suggest it, the google docs chat does not work with our computers. It is not the fault of the document, but probably a compatability error with our browser. It is because of this issue that we are going through this fun yet hasty process of making our own chat method.
Update
I decided to give up on my version of the chat using pure Google Apps Script and help improve my friends version using both G-A-S and HTML. I added image thumbnail/linking support with command /img or /image, along with improved time and counter, and some other behind the scenes updates. Here is a quick screenshot of it:
Magnificent chat programmed from scratch, and no buggy update methods, just a casual refresh database to check for messages and set HTML text-area text. No more buggy getText methods. For each new message in the database, whether targeted toward the user or toward everyone in the chat, we load all the database messages up to a limit (50 messages at a time), then display them. The use of HTML in the messages is key to its appearence and features, such as images.
function getChat() {
var chat = "";
var time = getTime();
var username = getCurrentUsername();
var db = ScriptDb.getMyDb();
var query = db.query({time : db.greaterThan(getJoinTime())}).sortBy('time', db.DESCENDING).limit(50);
var flag = query.getSize() % 2 != 0;
while(query.hasNext()) {
var record = query.next();
if(record.showTo == "all" || record.showTo == getCurrentUsername()) {
var text = record.text;
for(var i = 0; i < text.split(" ").length; i++) {
var substr = text.split(" ")[i];
if(substr.indexOf("http://") == 0 || substr.indexOf("https://") == 0) {
text = text.replace(substr, "<a href='" + substr + "'>" + substr + "</a>");
}
}
var message = "<pre style='display:inline;'><span class='" + (flag? "even" : "odd") + "'><b>[" + record.realTime + "]</b>" + text;
message += "</span></pre>";
chat += message;
flag = !flag;
}
}
//DocumentApp.getUi().alert(getTime() - time);
return chat;
}
I am going to re-do his getChat() method to only check for new messages, and not load every message at each refresh.
First thing to to to get rid of your error message is to create the UiApp in the createChat function instead of onOpen.
I also used a client handler to clear the textBox because it's just more efficient. Here is the modified code :
code removed see updates below
As for your second request I'm not sure I understand exactly what you want to do... could you explain more precisely the behavior you expect ? (this is more a comment than an answer but I used the "answer field" to be more readable)
EDIT : I played a little with this code and came to something that -almost- works... it still needs to be improved but it's worth showing how it works.
I used scriptProperties to store the common part of the conversation, I think that's a good approach but the issue it to know when to update its content. Here is the code I have so far, I keep being open to any suggestion/improvement of course.
code removed, new version below
EDIT 2 : here is a version with an auto update that works quite good, the script updates the chat area automatically for a certain time... if no activity then it stops and wait for a user action. please test (using 2 accounts) and let us know what you think.
note I used a checkBox to handler the autoUpdate, I keep it visible for test purpose but of course it could be hidden in a final version.
EDIT 3 : added a message to warn the user when he's been put offline + changed textBox to colored textArea to allow for longer messages + condition to clear the messageBox so that the warning message doesn't go in the conversation. (set the time out to a very short value for test purpose, change the counter value to restore to your needs)
function onOpen() {
if(getCurrentUser()=="dev1"||getCurrentUser()=="dev2"){ //user-Id's hidden for privacy
DocumentApp.getUi().createMenu('Chat')
.addItem('AutoColor', 'autoColor')
.addItem('Open Chat', 'createChatBox')
.addItem('Elements', 'displayElements') //Hidden as it is not important for regular use
.addItem('MyID', 'showUser')
.addToUi();
}else{
DocumentApp.getUi().createMenu('Chat')
.addItem('AutoColor', 'autoColor')
.addItem('Open Chat', 'createChatBox')
.addToUi();
}
}
function createChatBox(){
ScriptProperties.setProperty('chatContent','');
var app = UiApp.createApplication().setWidth(252);
app.setTitle("Chat Bar");
var vPanel = app.createVerticalPanel().setId('chatPanel').setWidth('100%');
var chatHandler = app.createServerHandler("sayChat").addCallbackElement(vPanel);
var textArea = app.createTextArea().setId('chatBox').setName('chatBox').setReadOnly(true).setText('').setSize('250px', '450px');
var textBox = app.createTextArea().setId('messageBox').setName('messageBox').setText('Start chat...').setPixelSize(250,100).setStyleAttributes({'padding':'5px','background':'#ffffcc'}).addKeyPressHandler(chatHandler);
var clearTextBoxClientHandler = app.createClientHandler().forTargets(textBox).setText('');
textBox.addClickHandler(clearTextBoxClientHandler);
var chatButton = app.createButton().setId("sayButton").setText("Say!").addMouseUpHandler(chatHandler);
var chkHandler = app.createServerHandler('autoUpdate').addCallbackElement(vPanel);
var chk = app.createCheckBox().setId('chk').addValueChangeHandler(chkHandler);
vPanel.add(textArea);
vPanel.add(textBox);
vPanel.add(chatButton);
vPanel.add(chk);
app.add(vPanel);
DocumentApp.getUi().showSidebar(app);
return app;
}
function sayChat(e){
var app = UiApp.getActiveApplication();
var user = '['+getCurrentUser()+'] : ';
if(e.parameter.messageBox=="You have been put offline because you didn't type anything for more than 5 minutes..., please click here to refresh the conversation"){
app.getElementById('messageBox').setText('');// clear messageBox
ScriptProperties.setProperty('chatTimer',0);// reset counter
return app;
}
if(e.parameter.source=='messageBox'&&e.parameter.keyCode!=13){return app};
var content = ScriptProperties.getProperty('chatContent');
ScriptProperties.setProperty('chatContent',content+"\n"+user+e.parameter.messageBox)
app.getElementById("chatBox").setText(content+"\n"+user+e.parameter.messageBox+'\n');
app.getElementById('messageBox').setText('');
app.getElementById('chk').setValue(true,true);
ScriptProperties.setProperty('chatTimer',0);
return app;
}
function autoUpdate(){
var app = UiApp.getActiveApplication();
var content = ScriptProperties.getProperty('chatContent');
var counter = Number(ScriptProperties.getProperty('chatTimer'));
++counter;
if(counter>20){
app.getElementById('chk').setValue(false);
app.getElementById('messageBox').setText("You have been put offline because you didn't type anything for more than 5 minutes..., please click here to refresh the conversation");
return app;
}
ScriptProperties.setProperty('chatTimer',counter);
var content = ScriptProperties.getProperty('chatContent');
app.getElementById("chatBox").setText(content+'*'); // the * is there only for test purpose
app.getElementById('chk').setValue(false);
Utilities.sleep(750);
app.getElementById('chk').setValue(true,true).setText('timer = '+counter);
return app;
}
function showUser(){
DocumentApp.getUi().alert("Your userId is: "+getCurrentUser());
}
function getCurrentUser(){
var email = Session.getEffectiveUser().getEmail();
return email.substring(0,email.indexOf("#"));
}

HTML5 Progress Element Scripting

I'm trying to display a HTML5 progress element to show the download progress of a large image file.
I've checked a few answers to similar questions already posted on this forum but they don't seem to directly answer the question (or more likely it's just my ignorance) or they get very technical and therefore way beyond me.
I've downloaded a HTML5 / JavaScript example file that shows the basic method (see code below) but I can't figure out how to link this script to my image download.
Any advice would be greatly appreciated.
<!DOCTYPE html>
<html>
<head>
<title>Developer Drive | Displaying the Progress of Tasks with HTML5 | Demo</title>
<script type="text/javascript">
var currProgress = 0;
var done = false;
var total = 100;
function startProgress() {
var prBar = document.getElementById("prog");
var startButt = document.getElementById("startBtn");
var val = document.getElementById("numValue");
startButt.disabled=true;
prBar.value = currProgress;
val.innerHTML = Math.round((currProgress/total)*100)+"%";
currProgress++;
if(currProgress>100) done=true;
if(!done)
setTimeout("startProgress()", 100);
else
{
document.getElementById("startBtn").disabled = false;
done = false;
currProgress = 0;
}
}
</script>
</head>
<body>
<p>Task progress:</p>
<progress id="prog" value="0" max="100"></progress>
<input id="startBtn" type="button" value="start" onclick="startProgress()"/>
<div id="numValue">0%</div>
</body>
</html>
If you are looking to track the progress of an XMLHttpRequest (which could be loading an image, or anything else), Adobe has a great example there. Ctrl+U is your friend :)
Basically, you'll want to do that:
var xhr = new XMLHttpRequest();
xhr.onprogress = function(e){
// This tests whether the server gave you the total number of bytes that were
// about to be sent; some servers don't (this is config-dependend), and
// without that information you can't know how far along you are
if (e.lengthComputable)
{
// e.loaded contains how much was loaded, while e.total contains
// the total size of the file, so you'll want to get the quotient:
progressBar.value = e.loaded / e.total * 100;
}
else
{
// You can't know the progress in term of percents, but you could still
// do something with `e.loaded`
}
};
Mozilla's Developer site has some more details, if you want to see what can be done.
Hope that's enough for you :)
PS: Now that I think about it, I see no reason not to use the e.total as progressBar.max, and simply push e.loaded into progressBar.value

Soundcloud HTML5 Player: Events.FINISH only fired once

I'm using the SC HTML5 player, when one sound finishes, I load in another source, however the FINISH event only seems to fire for the first song, my code is as follows
//Set the source
document.getElementById("sc-widget").src = scPath;
//get the widget reference
var widgetIframe = document.getElementById('sc-widget'),
widget = SC.Widget(widgetIframe);
//set the finish event
widget.bind(SC.Widget.Events.FINISH, endSC);
function endSC() {
var scPath = "http://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F1848538&show_artwork=true&auto_play=true";
document.getElementById("sc-widget").src = scPath;
var widgetIframe = document.getElementById('sc-widget'),
widget = SC.Widget(widgetIframe);
widget.bind(SC.Widget.Events.FINISH, endSC);
}
I've tried setting the endSC target to another function but that doesn't work, what am I missing? Thanks!
I had the same problem. SC.Widget method is working fine when I call it for the first time, but if I try to call it for the second time the console will fire "Uncaught TypeError: Cannot read property 'parentWindow' of null" error in http://w.soundcloud.com/player/api.js script. And that is where api.js script stops with actions (.Widget, .bind, etc.)
I found the solution. It's very weird, but it is a solution.
SoundCloud remote script is minified. Load it in your browser, C/P it in some online js beautifier and save it locally. Edit line 103 as follows:
return a.contentWindow;// || a.contentDocument.parentWindow
So I removed that .parentWindow call.
Save the file and call it in your page's head section. And that's it! Now FINISH event fires on every loaded widget.
I hope this will help.
Looks like this question is over 10 years old, but it just came up for me now.
I recreated the iframe div from scratch. Otherwise, the SC.Widget.Events.FINISH will only fire when the original embed player finishes.
You must reset the DOM element events by completely recreating the iframe element, like so:
//EXAMPLE SC SONG IDs
let songIds = [216109050, 779324239, 130928732]
let incrementingIndex = 0
function playSongsInIframe() {
let iframeParent = document.querySelector('#sound-player')
let iframeElement = document.querySelector('#sound-player iframe')
iframeElement.remove()
//CODE TO ADD NEW SOUND IDs
//yourSoundId = songIds[incrementingIndex]
let newIframe = document.createElement('iframe')
newIframe.id = "sound-" + yourSoundId
newIframe.width = "100%"
newIframe.height = "166"
newIframe.scrolling="no"
newIframe.frameborder="no"
newIframe.allow = "autoplay"
newIframe.src = "https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/" + yourSoundId + "&auto_play=true"
iframeParent.appendChild(newIframe)
let widget = SC.Widget("sound-" + yourSoundId);
widget.bind(SC.Widget.Events.READY, () => {
console.log('Ready...');
widget.play()
});
widget.bind(SC.Widget.Events.FINISH, () => {
console.log('Song ended...');
incrementingIndex++
playSongsInIframe()
});
}
One last consideration - this process must be started from a user event, like a click. You can add this function to the onclick attribute of an HTML button element:
<button onclick="playSongsInIframe()">Start Radio</button>