I get a console error while clicking a record Button.
I worked with the Code From RTCMulticonnection to establish a connection and now want to have the ability to record the stream. I used this demo to record the stream:
RecordRTC-and-RTCMultiConnection
https://github.com/muaz-khan/WebRTC-Experiment/blob/d1040f7dcd47c290f99ad51f9b3d57aa40c847c4/RTCMultiConnection/v2.2.2/demos/RecordRTC-and-RTCMultiConnection.html
The Console Message
Uncaught TypeError: Cannot read property 'YvuytsjuZSjrg1Wp9xa4jAXrEC783kpnW74r' of undefined
at HTMLButtonElement.button.onclick (index.html:108)
What I see is that in the demo version all streamid's have a short ID like
id="1mnvuzts2dm". My Version sets the streamid's to longer random strings like the one above in the Error id="YvuytsjuZSjrg1Wp9xa4jAXrEC783kpnW74r"
//RECORD THE CONVERSATION AUDIO + VIDEO
connection.onstream = function(e) {
appendVideo(e.mediaElement, e.streamid);
};
function appendVideo(video, streamid) {
video.width = 600;
video = getVideo(video, streamid);
videosContainer.appendChild(video);
rotateVideo(video);
scaleVideos();
}
function getVideo(video, streamid) {
var div = document.createElement('div');
div.className = 'video-container';
var button = document.createElement('button');
button.id = streamid;
button.innerHTML = 'Start Recording';
button.onclick = function() {
this.disabled = true;
if (this.innerHTML == 'Start Recording') {
this.innerHTML = 'Stop Recording';
connection.streams[this.id].startRecording({
audio: true,
video: true
});
} else {
this.innerHTML = 'Start Recording';
var stream = connection.streams[this.id];
stream.stopRecording(function(blob) {
var h2;
if (blob.audio && !(connection.UA.Chrome && stream.type == 'remote')) {
h2 = document.createElement('h2');
h2.innerHTML = 'Open recorded ' + blob.audio.type + '';
div.appendChild(h2);
}
if (blob.video) {
h2 = document.createElement('h2');
h2.innerHTML = 'Open recorded ' + blob.video.type + '';
div.appendChild(h2);
}
});
}
setTimeout(function() {
button.disabled = false;
}, 3000);
};
div.appendChild(button);
div.appendChild(video);
return div;
}
function rotateVideo(mediaElement) {
mediaElement.style[navigator.mozGetUserMedia ? 'transform' : '-webkit-transform'] = 'rotate(0deg)';
setTimeout(function() {
mediaElement.style[navigator.mozGetUserMedia ? 'transform' : '-webkit-transform'] = 'rotate(360deg)';
}, 1000);
}
connection.onstreamended = function(e) {
var div = e.mediaElement.parentNode;
div.style.opacity = 0;
rotateVideo(div);
setTimeout(function() {
if (div.parentNode) {
div.parentNode.removeChild(div);
}
scaleVideos();
}, 1000);
};
function scaleVideos() {
var videos = document.querySelectorAll('video'),
length = videos.length,
video;
var minus = 130;
var windowHeight = 700;
var windowWidth = 600;
var windowAspectRatio = windowWidth / windowHeight;
var videoAspectRatio = 4 / 3;
var blockAspectRatio;
var tempVideoWidth = 0;
var maxVideoWidth = 0;
for (var i = length; i > 0; i--) {
blockAspectRatio = i * videoAspectRatio / Math.ceil(length / i);
if (blockAspectRatio <= windowAspectRatio) {
tempVideoWidth = videoAspectRatio * windowHeight / Math.ceil(length / i);
} else {
tempVideoWidth = windowWidth / i;
}
if (tempVideoWidth > maxVideoWidth)
maxVideoWidth = tempVideoWidth;
}
for (var i = 0; i < length; i++) {
video = videos[i];
if (video)
video.width = maxVideoWidth - minus;
}
}
The ERROR Line is
connection.streams[this.id].startRecording({
You can use RecordRTC library to record the streams.
You just need to use this code in your primary page
and attach recordRTC library to your page.
recorder = connection.recorder;
if(!recorder)
{
recorder = RecordRTC([event.stream], {
type: 'video'
});
connection.recorder = recorder;
}
else {
recorder.getInternalRecorder().addStreams([event.stream]);
}
recorder.videoWidth = 500;
recorder.videoHeight = 500;
if(!connection.recorder.streams) {
connection.recorder.streams = [];
}
connection.recorder.streams.push(event.stream);
var length = connection.recorder.streams.length;
if(length > 2){
length = 2;
}
recordingStatus.innerHTML = 'Recording Started ' + length + ' streams';
Or you can use this code
connection.onstream = function(event) {
var video = document.createElement('video');
try {
video.setAttributeNode(document.createAttribute('autoplay'));
video.setAttributeNode(document.createAttribute('playsinline'));
} catch (e) {
video.setAttribute('autoplay', true);
video.setAttribute('playsinline', true);
}
if(event.type === 'local') {
video.volume = 0;
try {
video.setAttributeNode(document.createAttribute('muted'));
} catch (e) {
video.setAttribute('muted', true);
}
}
video.srcObject = event.stream;
var width = parseInt(connection.videosContainer.clientWidth / 3) - 20;
var mediaElement = getHTMLMediaElement(video, {
title: event.userid,
buttons: ['full-screen'],
width: width,
showOnMouseEnter: false
});
connection.videosContainer.appendChild(mediaElement);
setTimeout(function() {
mediaElement.media.play();
}, 5000);
mediaElement.id = event.streamid;
// to keep room-id in cache
localStorage.setItem(connection.socketMessageEvent, connection.sessionid);
if(chkRecordConference.checked === true) {
chkRecordConference.parentNode.style.display = 'none';
btnStopRecording.style.display = 'inline-block';
recordingStatus.style.display = 'inline-block';
recorder = connection.recorder;
if(!recorder)
{
recorder = RecordRTC([event.stream], {
type: 'video'
});
connection.recorder = recorder;
}
else {
recorder.getInternalRecorder().addStreams([event.stream]);
}
recorder.videoWidth = 500;
recorder.videoHeight = 500;
if(!connection.recorder.streams) {
connection.recorder.streams = [];
}
connection.recorder.streams.push(event.stream);
var length = connection.recorder.streams.length;
if(length > 2){
length = 2;
}
recordingStatus.innerHTML = 'Recording Started ' + length + ' streams';
}
If found how to do this thanks to this post, but as you can see by the code bellow I'm trying to console.log('Done'); when the time since the last click is greater than 2 seconds. However this doesn't work.
var lastClick = 0;
var button_pressed = false;
let button1 = document.getElementById('button1');
let button2 = document.getElementById('button2');
button1.onclick = function() {
button_pressed = true;
CheckAnswer();
}
button2.onclick = function() {
button_pressed = true;
CheckAnswer();
}
function CheckAnswer() {
if(button_pressed === true) {
var d = new Date();
var t = d.getTime();
if(t - lastClick < 2000) {
console.log('Continue');
}
} else if (t - lastClick > 2000) {
console.log('Done');
}
lastClick = t;
}
<button id="button1">Button1</button>
<button id="button2">Button2</button>
Thank you for your help.
The code never reaches the else if, because it requires button_pressed to be false
I fixed your code, see below.
The else if is now declared withtin the button_pressed === true statement.
function CheckAnswer() {
if(button_pressed === true) {
var d = new Date();
var t = d.getTime();
if(t - lastClick < 2000) {
console.log('Continue');
} else {
console.log('Done');
}
}
lastClick = t;
}
var lastClick = Date.now();
var button_pressed = false;
let button1 = document.getElementById('button1');
let button2 = document.getElementById('button2');
button1.onclick = function() {
button_pressed = true;
CheckAnswer();
}
button2.onclick = function() {
button_pressed = true;
CheckAnswer();
}
function CheckAnswer() {
var t = Date.now();
var diff = t - lastClick;
if(diff < 2000) {
console.log('Continue');
} else {
console.log('Done');
}
lastClick = t;
}
<button id="button1">Button1</button>
<button id="button2">Button2</button>
I'm creating 5 games with javascript and html5 and I'm using sound. I have a mute button that activates the function down bellow. Thing is, I want to make so that if I press the mute button and I move to another page, it will still be muted, but I can't seem to figure out how to integrate it in this function. If someone could help me out by editing the code, I'd really apreciate it :D
function init(){
audio = new Audio();
audio.src = "sound/paint_Music.mp3";
audio.loop = true;
audio.autoplay = true;
mutebtn = document.getElementById("mutebtn");
mutebtn.addEventListener("click", mute);
function mute(){
if (audio.muted){
audio.muted = false;
document.getElementById("mutebtn").src = "img/soundON.png";
} else {
audio.muted = true;
document.getElementById("mutebtn").src = "img/soundOFF.png";
}
}
}
Modify your function like this
function init() {
audio = new Audio();
audio.src = "sound/paint_Music.mp3";
audio.loop = true;
audio.autoplay = true;
var muteState = localStorage.getItem('muteState');
if (!muteState || muteState !== 'true') {
audio.muted = false;
document.getElementById("mutebtn").src = "img/soundON.png";
}
else {
audio.muted = true;
document.getElementById("mutebtn").src = "img/soundOFF.png";
}
mutebtn = document.getElementById("mutebtn");
mutebtn.addEventListener("click", mute);
function mute() {
if (audio.muted) {
audio.muted = false;
document.getElementById("mutebtn").src = "img/soundON.png";
} else {
audio.muted = true;
document.getElementById("mutebtn").src = "img/soundOFF.png";
}
localStorage.setItem('muteState', String(audio.muted));
}
}
Add the muted value to your localStorage in your 'mute' method.
function mute(){
...
audio.muted = false;
localStorage.setItem('muted', 'false');
} else {
audio.muted = true;
localStorage.setItem('muted', 'true');
}
}
}
Then on your init retrieve the localStorage value or default to false if it wasn't set prior.
function init(){
audio = new Audio();
audio.src = "sound/paint_Music.mp3";
audio.loop = true;
audio.autoplay = true;
var isMuted = (localStorage.getItem("muted") && localStorage.getItem("muted") == 'true') || false
audio.muted = isMuted;
mutebtn = document.getElementById("mutebtn");
mutebtn.addEventListener("click", mute);
}
I'm not sure if this is possible, here is what I mean:
I have a touch event to hide/show an hourly forecast, but now I need to make the touch event on a separate HTML file, so when I tap the touch event on one html file the forecast (displayed in a separate html file) will disappear, can this be done?
Here is my js file for all the touch events:
// UniAW6.4LS By Ian Nicoll and Dacal
var forecastdisplay = true;
var hourlyforecastdisplay = true;
var slideshow = false;
var optiondisplay = false;
var weatherdisplay = true;
var weatherBGdisplay = true;
var clockdisplay = true;
var timedwalls = false;
var disabletouch = false;
var windeffectdisplay = true;
var prev_wind_effects = wind_effects; // TO REVERT BACK...
var touchdownX;
var touchupX;
var touchX;
var stateX = 0;
var stateY = 0;
if (ChangeClick == false) { var touchmode = "touchend"; } else { var touchmode = "click"; }
function StartTouch() {
if (ChangeClick == false) {
document.getElementById("HourlyTouchLayer").addEventListener("touchstart", touchStart, false); // FOR THE HOURLY FORECAST
document.getElementById("HourlyTouchLayer").addEventListener("touchmove", touchMove, false); // FOR THE HOURLY FORECAST
} else {
document.getElementById("HourlyTouchLayer").addEventListener("mousedown", mouseDown, false); // FOR THE HOURLY FORECAST
document.getElementById("HourlyTouchLayer").addEventListener("mouseup", mouseUp, false); // FOR THE HOURLY FORECAST
}
document.getElementById("TouchLayer").addEventListener(touchmode, touchEnd, false); // FOR THE FORECAST
document.getElementById("TouchLayer2").addEventListener(touchmode, touchEnd2, false); // FOR THE OPTIONS
}
function touchEnd() {
if (forecastdisplay == false) {
document.getElementById('TouchForecast').className = "forecastMoveUp";
forecastdisplay = true;
} else {
document.getElementById('TouchForecast').className = "forecastMoveDown";
forecastdisplay = false;
}
if (updateFileTimer != "") { createOptionsCookie(); }
}
function touchEnd2(event) {
event.preventDefault();
if (optiondisplay == false) {
document.getElementById("optionContainer").style.zIndex= "1000";
document.getElementById("optionContainer").className = "fade-in-option";
StartButtons();
optiondisplay = true;
} else {
document.getElementById("optionContainer").style.zIndex= "800";
document.getElementById("optionContainer").className = "fade-out-option";
StopButtons();
optiondisplay = false;
}
}
function touchStart(event) {
event.preventDefault();
touchdownX = event.targetTouches[0].pageX;
}
function touchMove(event) {
event.preventDefault();
touchupX = event.targetTouches[0].pageX;
touchX = touchupX - touchdownX;
if (touchX != 0) { MoveElementX(); }
}
function mouseDown(event) {
event.preventDefault();
touchdownX = event.pageX;
}
function mouseUp(event) {
event.preventDefault();
touchupX = event.pageX;
touchX = touchupX - touchdownX;
if (touchX != 0) { MoveElementX(); }
}
function MoveElementX() {
if (hourlyforecastdisplay == true) {
switch (stateX) {
case 0 :
if ( touchX < 0 ) {
document.getElementById("hourlyforecast").className = "forecastTranslateLeft";
stateX++;
}
break;
case 1 :
if ( touchX > 0 ) {
document.getElementById("hourlyforecast").className = "forecastTranslateRight";
stateX--;
}
break;
}
}
}
function StartButtons() {
document.getElementById("refresh").addEventListener(touchmode, touchRefresh, false);
document.getElementById("timedwall").addEventListener(touchmode, touchTimewall, false);
document.getElementById("slideshow").addEventListener(touchmode, touchSlideShow, false);
document.getElementById("hideweatherInfo").addEventListener(touchmode, touchHideWeather, false);
document.getElementById("hideweatherBG").addEventListener(touchmode, touchHideWeatherBG, false);
document.getElementById("hideclock").addEventListener(touchmode, touchHideClock, false);
document.getElementById("disableforcasttouch").addEventListener(touchmode, touchDisableForecast, false);
document.getElementById("windeffect").addEventListener(touchmode, touchWindeffect, false);
document.getElementById("disablehourlyforcast").addEventListener(touchmode, touchHideHourlyForecast, false);
document.getElementById("refresh").innerHTML = "Reload (for a fresh start)";
document.getElementById("timedwall").innerHTML = "Launch Timed Walls";
document.getElementById("slideshow").innerHTML = "Launch the Slideshow";
document.getElementById("hideweatherInfo").innerHTML = "Hide all weather information";
document.getElementById("hideweatherBG").innerHTML = "Hide all overlay";
document.getElementById("hideclock").innerHTML = "Hide the clock";
document.getElementById("disableforcasttouch").innerHTML = "Disable forecast touch";
document.getElementById("windeffect").innerHTML = "Disable Wind Effect";
document.getElementById("disablehourlyforcast").innerHTML = "Hide Hourly Forecast";
}
function StopButtons() {
document.getElementById("refresh").removeEventListener(touchmode, touchRefresh, false);
document.getElementById("timedwall").removeEventListener(touchmode, touchTimewall, false);
document.getElementById("slideshow").removeEventListener(touchmode, touchSlideShow, false);
document.getElementById("hideweatherInfo").removeEventListener(touchmode, touchHideWeather, false);
document.getElementById("hideweatherBG").removeEventListener(touchmode, touchHideWeatherBG, false);
document.getElementById("hideclock").removeEventListener(touchmode, touchHideClock, false);
document.getElementById("disableforcasttouch").removeEventListener(touchmode, touchDisableForecast, false);
document.getElementById("windeffect").removeEventListener(touchmode, touchWindeffect, false);
document.getElementById("disablehourlyforcast").removeEventListener(touchmode, touchHideHourlyForecast, false);
}
function touchRefresh() {
event.preventDefault();
$.removeCookie('optionsCookie');
window.location.reload();
}
function touchTimewall() {
if (timedwalls == false) {
if (slideshow == true) { touchSlideShow(); }
timedwalls = true;
Wallpaper_options = 'timedwalls';
document.getElementById("backgroundContainer").className = "fade-out-wall";
document.getElementById("timedwall").className = "TextColorGreen";
} else {
timedwalls = false;
wpidx = "-1";
WPfade_inTW.className='fade-out-wall';
WPfade_outTW.className='fade-out-wall';
document.getElementById("backgroundContainer").className = "fade-in-wall";
document.getElementById("timedwall").className = "TextColorWhite";
}
if (optiondisplay == true) { createOptionsCookie(); } // SAVE THE CONFIGURATION
}
function touchSlideShow() {
if (slideshow == false) {
if (timedwalls == true) { touchTimewall(); } // STOP THE TIMED WALL
widgetStart();
slideshow = true;
Wallpaper_options = 'slideshow';
document.getElementById("slideshow").className = "TextColorGreen";
if (filename != "") {
clearInterval(meteorTimer);
delelement("astronautContainer");
delelement("fogContainer");
delelement("starContainer");
delelement("meteorContainer");
delelement("frameContainer");
delelement("cloudContainer");
delelement("dropContainer");
delelement("circleContainer");
delelement("wiperContainer");
delelement("starsBGContainer");
delelement("windContainer");
delelement("windmillContainer");
delelement("big_balloonContainer");
delelement("small_balloonContainer");
delelement("birdsContainer");
delelement("frostContainer");
if (Show_wind_effects == true) {
removejscssfile("Weather/"+iPhoneType, wind_effects+"_effects", "css");
removejscssfile("Weather/"+iPhoneType, wind_effects+"_effects", "js");
Show_wind_effects = false;
}
if (Show_frost == true) {
removejscssfile("Weather/" + iPhoneType, "frost_effect", "css");
removejscssfile("Weather/" + iPhoneType, "frost_effect", "js");
Show_frost = false;
}
removejscssfile("Weather/"+iPhoneType, filename, "css");
removejscssfile("Weather/"+iPhoneType, filename, "js");
}
document.getElementById("sun_moonContainer").className = "fade-out-wall";
document.getElementById("backgroundContainer").className = "fade-out-wall";
} else {
widgetStop();
slideshow = false;
if (filename != "") {
loadjscssfile ("Weather/"+iPhoneType, filename, "css");
loadjscssfile ("Weather/"+iPhoneType, filename, "js");
if (Start_wind_effects == true) {
loadjscssfile ("Weather/"+iPhoneType, wind_effects+"_effects", "css");
loadjscssfile ("Weather/"+iPhoneType,wind_effects+"_effects", "js");
Show_wind_effects = true;
}
if (Start_frost == true) {
loadjscssfile("Weather/" + iPhoneType, "frost_effect", "css");
loadjscssfile("Weather/" + iPhoneType, "frost_effect", "js");
Show_frost = true;
}
}
document.getElementById("sun_moonContainer").className = "fade-in-wall";
document.getElementById("backgroundContainer").className = "fade-in-wall";
document.getElementById("slideshow").className = "TextColorWhite";
}
if (optiondisplay == true) { createOptionsCookie(); } // SAVE THE CONFIGURATION
}
function touchHideWeather() {
if (weatherdisplay == true) {
document.getElementById("WeatherInfo").className = "fade-out-wall";
document.getElementById("forecastInfo").className = "fade-out-wall";
document.getElementById("hourlyforecast").className = "fade-out-wall";
weatherdisplay = false;
document.getElementById("hideweatherInfo").className = "TextColorGreen";
} else {
document.getElementById("WeatherInfo").className = "fade-in-wall";
document.getElementById("forecastInfo").className = "fade-in-wall";
document.getElementById("hourlyforecast").className = "fade-in-wall";
weatherdisplay = true;
document.getElementById("hideweatherInfo").className = "TextColorWhite";
}
if (optiondisplay == true) { createOptionsCookie(); } // SAVE THE CONFIGURATION
}
function touchHideClock() {
if (clockdisplay == true) {
document.getElementById("clockContainer").className = "fade-out-wall";
clockdisplay = false;
document.getElementById("hideclock").className = "TextColorGreen";
} else {
document.getElementById("clockContainer").className = "fade-in-wall";
clockdisplay = true;
document.getElementById("hideclock").className = "TextColorWhite";
}
if (optiondisplay == true) { createOptionsCookie(); } // SAVE THE CONFIGURATION
}
function touchHideWeatherBG() {
if (weatherBGdisplay == true) {
document.getElementById("forecastbg").style.display = 'none';
document.getElementById("hourlyforecastbg").style.display = 'none';
document.getElementById("WeatherInfoBG").className = "fade-out-wall";
weatherBGdisplay = false;
document.getElementById("hideweatherBG").className = "TextColorGreen";
} else {
document.getElementById("forecastbg").style.display = 'block';
document.getElementById("hourlyforecastbg").style.display = 'block';
document.getElementById("WeatherInfoBG").className = "fade-in-wall";
weatherBGdisplay = true;
document.getElementById("hideweatherBG").className = "TextColorWhite";
}
if (optiondisplay == true) { createOptionsCookie(); } // SAVE THE CONFIGURATION
}
function touchDisableForecast() {
if (disabletouch == true) {
document.getElementById("TouchLayer").addEventListener(touchmode, touchEnd, false);
disabletouch = false;
document.getElementById("disableforcasttouch").className = "TextColorWhite";
} else {
document.getElementById("TouchLayer").removeEventListener(touchmode, touchEnd, false);
disabletouch = true;
document.getElementById("disableforcasttouch").className = "TextColorGreen";
}
if (optiondisplay == true) { createOptionsCookie(); } // SAVE THE CONFIGURATION
}
function touchWindeffect() {
if (windeffectdisplay == true) {
prev_wind_effects = wind_effects;
wind_effects = "none";
Start_wind_effects = false;
windeffectdisplay = false;
document.getElementById("windeffect").className = "TextColorGreen";
if (Show_wind_effects == true) {
delelement("windContainer");
delelement("windmillContainer");
removejscssfile("Weather/"+iPhoneType, wind_effects+"_effects", "css");
removejscssfile("Weather/"+iPhoneType, wind_effects+"_effects", "js");
Show_wind_effects = false;
}
} else {
wind_effects = prev_wind_effects;
if ((filename != "") && (slideshow == false) && (Show_wind_effects == false)) {
if ((Math.round(obj.windspeed) >= Strong_Wind) && (filename != "windy") && (wind_effects != "none")) { Start_wind_effects = true; } else { Start_wind_effects = false; }
if (Start_wind_effects == true) {
loadjscssfile ("Weather/"+iPhoneType, wind_effects+"_effects", "css");
loadjscssfile ("Weather/"+iPhoneType, wind_effects+"_effects", "js");
Show_wind_effects = true;
}
}
windeffectdisplay = true;
document.getElementById("windeffect").className = "TextColorWhite";
}
if (optiondisplay == true) { createOptionsCookie(); } // SAVE THE CONFIGURATION
}
function touchHideHourlyForecast() {
if (hourlyforecastdisplay == true) {
document.getElementById("hourlyforecast").className = "fade-out-wall";
document.getElementById("hourlyforecastbg").style.display = 'none';
hourlyforecastdisplay = false;
document.getElementById("disablehourlyforcast").className = "TextColorGreen";
} else {
document.getElementById("hourlyforecast").className = "fade-in-wall";
document.getElementById("hourlyforecastbg").style.display = 'block';
hourlyforecastdisplay = true;
document.getElementById("disablehourlyforcast").className = "TextColorWhite";
}
if (optiondisplay == true) { createOptionsCookie(); } // SAVE THE CONFIGURATION
}
function createOptionsCookie() {
var options = {};
options.slideshow = slideshow;
options.clockdisplay = clockdisplay;
options.weatherdisplay = weatherdisplay;
options.timedwalls = timedwalls;
options.weatherBGdisplay = weatherBGdisplay;
options.disabletouch = disabletouch;
options.forecastdisplay = forecastdisplay;
options.windeffectdisplay = windeffectdisplay;
options.hourlyforecastdisplay = hourlyforecastdisplay;
var optionsTmp = JSON.stringify(options);
$.cookie('optionsCookie', optionsTmp, {expires: 365});
}
Does the page receiving the touch event have a reference (or can get a reference) to the forecast page? For example, is the forecast page in an iframe inside the original page?
If so, you could use postMessage() to communicate from the original page to the forecast page.
OTOH, if the forecast page is inside an iframe, and all you want to do is remove the forecast entirely, then all you really need to do is have the original page remove the iframe from the DOM.
I'd be happy to talk about any approach in more detail, but first how about providing some more information about these pages and how they are loaded?
Without developing a data-driven backend (PHP, Node, RoR - to name the most popular), your best bet is probably working with LocalStorage.
var foo = localStorage.getItem("bar");
// ...
localStorage.setItem("bar", foo);
When handling the touch event, you could set a variable with localStorage, and then in the other HTML page, look for a corresponding item and act on the value (or lack thereof) of that value.
You may also want to hook into the localStorage change event - just "storage":
HTML5 / JS storage event handler
document.addEventListener('storage', storageEventHandler, false);
var storageEventHandler = function(event){
//do something
}
Trust me, I hate these just as much as you. It's for a client though so it's not up to me to determine what they should be doing :)
here's how you use it:
<script type="text/javascript">
var exitsplashmessage = 'Please dont go!';
var exitsplashpage = 'http://www.site.com/exitpage/';
</script>
<script type="text/javascript" src="/exit.js"></script>
the problem is it loads it into an iframe, which isnt really what I want to do. I want to just have it redirect to the page which is defined with exitsplashpage;
Here is the exit.js code:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function () {
if (oldonload) {
oldonload();
}
func();
}
}
}
function addClickEvent(a, i, func) {
if (typeof a[i].onclick != 'function') {
a[i].onclick = func;
}
}
var theDiv = '<div id="ExitSplashDiv" style="display:block; width:100%; height:100%; position:absolute; background:#FFFFFF; margin-top:0px; margin-left:0px;" align="center">';
theDiv = theDiv + '<iframe src="' + exitsplashpage + '" width="100%" height="100%" align="middle" frameborder="0"></iframe>';
theDiv = theDiv + '</div>';
theBody = document.body;
if (!theBody) {
theBody = document.getElementById("body");
if (!theBody) {
theBody = document.getElementsByTagName("body")[0];
}
}
var PreventExitSplash = false;
function DisplayExitSplash() {
if (PreventExitSplash == false) {
window.scrollTo(0, 0);
PreventExitSplash = true;
divtag = document.createElement("div");
divtag.setAttribute("id", "ExitSplashMainOuterLayer");
divtag.style.position = "absolute";
divtag.style.width = "100%";
divtag.style.height = "100%";
divtag.style.zIndex = "99";
divtag.style.left = "0px";
divtag.style.top = "0px";
divtag.innerHTML = theDiv;
theBody.innerHTML = "";
theBody.topMargin = "0px";
theBody.rightMargin = "0px";
theBody.bottomMargin = "0px";
theBody.leftMargin = "0px";
theBody.style.overflow = "hidden";
theBody.appendChild(divtag);
return exitsplashmessage;
}
}
var a = document.getElementsByTagName('A');
for (var i = 0; i < a.length; i++) {
if (a[i].target !== '_blank') {
addClickEvent(a, i, function () {
PreventExitSplash = true;
});
} else {
addClickEvent(a, i, function () {
PreventExitSplash = false;
});
}
}
disablelinksfunc = function () {
var a = document.getElementsByTagName('A');
for (var i = 0; i < a.length; i++) {
if (a[i].target !== '_blank') {
addClickEvent(a, i, function () {
PreventExitSplash = true;
});
} else {
addClickEvent(a, i, function () {
PreventExitSplash = false;
});
}
}
}
addLoadEvent(disablelinksfunc);
disableformsfunc = function () {
var f = document.getElementsByTagName('FORM');
for (var i = 0; i < f.length; i++) {
if (!f[i].onclick) {
f[i].onclick = function () {
PreventExitSplash = true;
}
} else if (!f[i].onsubmit) {
f[i].onsubmit = function () {
PreventExitSplash = true;
}
}
}
}
addLoadEvent(disableformsfunc);
window.onbeforeunload = DisplayExitSplash;
Replace DisplayExitSplash() function with this
function DisplayExitSplash() {
if (PreventExitSplash == false) {
window.scrollTo(0, 0);
PreventExitSplash = true;
divtag = document.createElement("div");
divtag.setAttribute("id", "ExitSplashMainOuterLayer");
divtag.style.position = "absolute";
divtag.style.width = "100%";
divtag.style.height = "100%";
divtag.style.zIndex = "99";
divtag.style.left = "0px";
divtag.style.top = "0px";
divtag.innerHTML = theDiv;
theBody.innerHTML = "";
theBody.topMargin = "0px";
theBody.rightMargin = "0px";
theBody.bottomMargin = "0px";
theBody.leftMargin = "0px";
theBody.style.overflow = "hidden";
theBody.appendChild(divtag);
window.location.href = exitsplashpage;
return exitsplashmessage;
}
}
Would this work?
function DisplayExitSplash() {
window.location = exitsplashpage;
}
You could re-define the DisplayExitSplash function:
<script type="text/javascript">
var exitsplashmessage = 'Please dont go!';
var exitsplashpage = 'http://www.site.com/exitpage/';
</script>
<script type="text/javascript" src="/exit.js"></script>
<script type="text/javascript">
DisplayExitSplash = function () {
window.location.href = exitsplashpage;
};
window.onbeforeunload = DisplayExitSplash;
</script>
JSFiddle exemplifying the concept:
http://jsfiddle.net/hFXPE/