Offline storage in firefox 3.5 for file:// - javascript

I was trying out the code for offline storage in firefox 3.5, taken from http://starkravingfinkle.org/blog/2008/05/firefox-3-offline-app-demo-part-2/.
When the page loads i get a dialog prompting me that the application is asking for storing data, but when i press Allow, the dialog does not go away . The app works fine at the online demo given on the website.
The source file containing the javascript is as follows :
todo.html
<!--
Simple task list application used to illusrate Firefox's offline/DOMStorage capabilities
Author: Mark Finkle
-->
<html manifest="todo.manifest">
<head>
<title>TODO - Offline Demo</title>
<script type="text/javascript" src="json.js"></script>
<script language="javascript">
var taskStorage = "[]";
var storageDomain = location.hostname;
if (storageDomain == "localhost")
storageDomain += ".localdomain";
function loaded() {
updateOnlineStatus("load", false);
document.body.addEventListener("offline", function () { updateOnlineStatus("offline", true) }, false);
document.body.addEventListener("online", function () { updateOnlineStatus("online", true) }, false);
if (typeof globalStorage != "undefined") {
var storage = globalStorage[storageDomain];
if (storage && storage.taskStorage) {
taskStorage = storage.taskStorage;
}
}
fetchList();
}
function updateOnlineStatus(msg, allowUpdate) {
var status = document.getElementById("status");
status.innerHTML = (navigator.onLine ? "[online]" : "[offline]");
var log = document.getElementById("log");
log.appendChild(document.createTextNode("Event: " + msg + "\n"));
if (navigator.onLine && allowUpdate) {
update();
log.appendChild(document.createTextNode("Updated server\n"));
}
}
function httpRequest(type, data, callback) {
var httpreq = new XMLHttpRequest();
httpreq.onreadystatechange = function() { if (httpreq.readyState == 4) callback(httpreq.readyState, httpreq.status, httpreq.responseText); };
httpreq.open(type, "todo-server.php", true);
if (type == "POST") {
httpreq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
httpreq.send(data);
}
function loadList(readyState, status, responseText) {
if (readyState == 4) {
if (status == 200) {
taskStorage = responseText;
var tasks = eval("(" + taskStorage + ")");
var html = "";
for (var i=0; i<tasks.length; i++) {
html += "<input type='checkbox' id='" + tasks[i].name + "'/><label for='" + tasks[i].name + "'>" + tasks[i].data + "</label><br/>";
}
document.getElementById("tasklist").innerHTML = html;
if (typeof globalStorage != "undefined") {
globalStorage[storageDomain].taskStorage = taskStorage;
}
}
}
}
function fetchList() {
if (navigator.onLine) {
httpRequest("GET", null, loadList);
}
else {
loadList(4, 200, taskStorage);
}
}
function addItem() {
var data = document.getElementById("data").value;
document.getElementById("data").value = "";
var tasks = eval("(" + taskStorage + ")");
tasks.push({"name": Date.now(), "data": data });
taskStorage = tasks.toJSONString();
update();
}
function removeItems() {
var tasks = eval("(" + taskStorage + ")");
var newTasks = [];
var items = document.getElementById("tasklist").getElementsByTagName("input");
for (var i=0; i<items.length; i++) {
if (items[i].checked == false) {
newTasks.push(tasks[i]);
}
}
taskStorage = newTasks.toJSONString();
update();
}
function completeItems() {
var tasks = eval("(" + taskStorage + ")");
var items = document.getElementById("tasklist").getElementsByTagName("input");
for (var i=0; i<items.length; i++) {
if (items[i].checked) {
var task = tasks[i].data;
if (task.indexOf("<strike>") != -1) {
task = task.replace("<strike>", "");
task = task.replace("</strike>", "");
}
else {
task = "<strike>" + task + "</strike>";
}
tasks[i].data = task;
}
}
taskStorage = tasks.toJSONString();
update();
}
function update() {
if (navigator.onLine) {
var post = "action=update&data=";
post += encodeURIComponent(taskStorage);
httpRequest("POST", post, function(readyState, status, json) { fetchList(); });
}
else {
loadList(4, 200, taskStorage);
}
}
</script>
<style type="text/css">
body { font-family: verdana,tahoma, arial; }
div#container { width: 300px; }
div#title { font-size: 120%; }
div#subtitle { font-size: 80%; }
div#tasklist { margin-bottom: .5em; }
div#log { font-size: 90%; background-color: lightgray; margin-top: 1em; white-space: pre; }
</style>
</head>
<body onload="loaded();">
<div id="container">
<div id="title">Task Helper - <span id="status">ONLINE</span></div>
<div id="subtitle">simple online/offline demo application</div>
<hr />
<div id="tasklist">
</div>
<input type="text" id="data" size="35" />
<input type="button" value="Add" onclick="addItem();"/>
<hr />
<input type="button" value="Remove" onclick="removeItems();"/>
<input type="button" value="Complete" onclick="completeItems();"/>
<div id="log"><strong>Event Log</strong>
</div>
</div>
</body>
</html>

I believe that the localStorage api is replacing globalStorage in FF 3.5. You can read more about it here: https://developer.mozilla.org/en/DOM/Storage
I think the api is very similar, so you could try something like this:
var storage;
if (typeof localStorage != "undefined") {
storage = localStorage;
}
else if (typeof globalStorage != "undefined") {
storage = globalStorage[storageDomain];
}
if (storage && storage.taskStorage) {
taskStorage = storage.taskStorage;
}
Hope that helps!
EDIT: Anywhere you use globalStorage, you'll have to check for localStorage as well. Or promote the storage variable up in scope and detect it once.

So after reading the question twice, I think I understood the question: you're asking about using globalStorage in file:/// documents.
globalStorage (as well as localStorage) doesn't work very well in file:/// documents as of Firefox 3.5. I didn't see the specific bug report about this issue, but since globalStorage is deprecated in favor of localStorage, it doesn't really matter.
If you're just testing it out, install some kind of web server locally, it's not complicated at all.

Related

Uncaught TypeError: Cannot read property addEventListener of null

Im working on an assignment for my javascript class, and I keep getting the error
fetch_page.js:109 Uncaught TypeError: Cannot read property 'addEventListener' of null
at addEventListeners (fetch_page.js:109)
at fetch_page.js:121
I'll be honost, I don't understand javascript for crap, but I'm forced to take this class for my network admin degree. Can anyone point out where I'm making this error?
window.addEventListener('DOMContentLoaded', (function() {
var contents;
var protocol;
var hostname;
var directory;
var file;
function parseBase() {
var pos, slashPos;
var remainder;
pos = BASE.indexOf('://');
protocol = BASE.substr(0, pos);
remainder = BASE.substr(pos + 3);
slashPos = remainder.indexOf('/');
if (slashPos === -1) {
hostname = remainder;
directory = "";
file = "";
} else {
hostname = remainder.substr(0, slashPos);
remainder = remainder.substr(slashPos + 1);
slashPos = remainder.lastIndexOf('/');
if (slashPos === -1) {
directory = "";
file = remainder;
} else {
directory = remainder.substr(0, slashPos);
file = remainder.substr(slashPos + 1);
}
}
console.log("protocol:", protocol);
console.log("hostname:", hostname);
console.log("directory:", directory);
console.log("file:", file);
}
function relativeToAbsolute(url) {
if (url.indexOf('://') > -1) { // http://somedomain.com/path/file.html
return url;
} else if (url[0] === '/') { // /path/file.html
return protocol + "://" + hostname + url;
} else { // path/file.html
if (directory === "") {
return protocol + "://" + hostname + "/" + url;
} else {
return protocol + "://" + hostname + "/" + directory + "/" + url;
}
}
}
function parsePage() {
var parser = new DOMParser();
contents = parser.parseFromString(atob(PAGE), "text/html");
console.log(contents);
}
function moveChildren(source, destination) {
while (source.childNodes.length > 0) {
var child = source.childNodes[0];
source.removeChild(child);
destination.appendChild(child);
}
}
function fixTags(tagName, attribute) {
var tags = contents.getElementsByTagName(tagName);
for (var counter = 0; counter < tags.length; counter++) {
var url = tags[counter].getAttribute(attribute);
if (url) {
tags[counter].setAttribute(attribute, relativeToAbsolute(url));
}
}
}
function fixRedirectedTags(tagName, attribute) {
var tags = contents.getElementsByTagName(tagName);
for (var counter = 0; counter < tags.length; counter++) {
var url = tags[counter].getAttribute(attribute);
if (url) {
tags[counter].setAttribute(attribute,
window.location.origin + window.location.pathname + '?url=' + encodeURIComponent(relativeToAbsolute(url)));
}
}
}
function fixURLs() {
fixTags('img', 'src');
fixTags('script', 'src');
fixTags('link', 'href');
fixRedirectedTags('a', 'href');
}
function moveContent() {
moveChildren(contents.head, document.head);
moveChildren(contents.body, document.getElementById('contents'));
}
function submit() {
console.log("submitted:", encodeURIComponent(document.getElementById('urlBox').value));
}
function addEventListeners() {
document.getElementById('goButton').addEventListener('click', submit);
document.getElementById('urlBox').addEventListener('keydown', function(event) {
if (event.keyCode == 13 || event.keyCode == 10) {
submit();
}
});
}
return function() {
parseBase();
parsePage();
fixURLs();
moveContent();
addEventListeners();
}
})())
body {
margin: 0px;
}
#searchBox {
background: black;
color: white;
width: 100%;
text-align: center;
vertical-align: middle;
padding: 10px;
}
#goButton {
background: red;
color: black;
padding: 4px
font-weight: bold;
font-family: Arial;
font-size: .75em;
vertical-align: middle;
cursor: pointer;
}
#urlBox {
width: 50%
}
#contents {
border: 1px solid black;
}
<?php
$url = isset ($_GET['url']) ? $_GET['url'] : "http://eloquentjavascript.net/";
$contents = base64_encode(mb_convert_encoding(file_get_contents($url), "HTML-ENTITIES","UTF-8"));
?>
<!doctype html>
<html>
<head>
<title>Fetch Page</title>
<link rel="stylesheet" href="fetch_page.css">
<script src="fetch_page.js"></script>
<script>
var BASE = "<?php echo $url; ?>";
var PAGE = "<?php echo $contents; ?>";
</script>
</head>
<body>
<div id="searchBox">Type a URL here: <input type="text" id=urlBox"> <span id="goButton">GO</span></div>
<div id="tocContainer">
<div id="toc">[toc goes here]</div>
<p id="contents">Hello World!</p>
<div id="contents"></div>
</body>
</html>
What does your error mean?
Uncaught TypeError: Cannot read property 'addEventListener' of null.
at addEventListeners
That boils down to:
You've tried to access the addEventListener property of something in the addEventListeners function, but that's null.
Take a look at addEventListeners:
document.getElementById('goButton').addEventListener('click', submit);
document.getElementById('urlBox').addEventListener('keydown', function(event) {
if (event.keyCode == 13 || event.keyCode == 10) {
submit();
}
});
One of the getElementsById calls has returned null, indicating that there's no such ID in your code.
After looking at the HTML, you can see that the problem is at the following place:
<input type="text" id=urlBox">
You're missing the opening quote at the ID, so really you've given your element the ID of urlBox" (you can omit quotes around a HTML attribute, but not recommended though).
That's why the JS can't find the element with ID urlBox
Just experienced something similar. Adding a defer to my script tag solved the issue:
<script src="fetch_page.js" defer></script>
Good luck! ~E
One of these two document.getElementById calls is returning null, because there's no element with that Id. You can add a breakpoint in the debug console in the code, or add a console.log to figure out exactly where the problem is occuring
document.getElementById('goButton').addEventListener('click', submit);
document.getElementById('urlBox').addEventListener('keydown', function(event) {
Apart from any typing error like eg. omitting quotes, try defer in the <script src ... line of the html code. I solved my problem in this way!
I had this problem too and I checked my code and everything was in other. I realized that it was where I positioned my script tag i.e the head of the html file so I then put it at the end of my body tag. I also found out that from one of the guys who answered this question that using "defer" makes it work no matter where the script tag is as long as it's inside the html tag.
Add window.onload = function() {<enter your javascript code here}; to your script. That easy.

Why RTCMultiConnection Event Type is always 'local'?

I'm trying to create a basic video chat using RTCMultiConnection Webrtc.
The code works fine in Safari browser but it always fails to show the joiners videos in a simple ios phonegap app. so basically no one can see others videos.
I added iosrtc plugin to my app as well...
Spent days trying to find the issue and I think I am getting close.
I found out that the event.type is always local for everyone.
So, the event.type is never remote for anyone that uses the app.
But when i test the same code in safari browser, the first joiner event.type is local and the rest of the joiners event.type is remote and thats why it works fine in the browser.
Now that I found the issue (sort of), I need to know why this is happening in the phonegap app and how to eradicate it.
This is my entire code, you can run this code directly in your browser as is and it will work fine:
Javascript:
// ......................................................
// .......................UI Code........................
// ......................................................
document.getElementById('open-room').onclick = function() {
disableInputButtons();
connection.open(document.getElementById('room-id').value, function(isRoomOpened, roomid, error) {
if(isRoomOpened === true) {
showRoomURL(connection.sessionid);
}
else {
disableInputButtons(true);
if(error === 'Room not available') {
alert('Someone already created this room. Please either join or create a separate room.');
return;
}
alert(error);
}
});
};
document.getElementById('join-room').onclick = function() {
disableInputButtons();
connection.join(document.getElementById('room-id').value, function(isJoinedRoom, roomid, error) {
if (error) {
disableInputButtons(true);
if(error === 'Room not available') {
alert('This room does not exist. Please either create it or wait for moderator to enter in the room.');
return;
}
alert(error);
}
});
};
document.getElementById('open-or-join-room').onclick = function() {
disableInputButtons();
connection.openOrJoin(document.getElementById('room-id').value, function(isRoomExist, roomid, error) {
if(error) {
disableInputButtons(true);
alert(error);
}
else if (connection.isInitiator === true) {
// if room doesn't exist, it means that current user will create the room
showRoomURL(roomid);
}
});
};
// ......................................................
// ..................RTCMultiConnection Code.............
// ......................................................
var connection = new RTCMultiConnection();
// by default, socket.io server is assumed to be deployed on your own URL
//connection.socketURL = '/';
// comment-out below line if you do not have your own socket.io server
connection.socketURL = 'https://rtcmulticonnection.herokuapp.com:443/';
connection.socketMessageEvent = 'video-conference-demo';
connection.session = {
audio: true,
video: true
};
connection.sdpConstraints.mandatory = {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true
};
connection.videosContainer = document.getElementById('videos-container');
connection.onstream = function(event) {
var video = document.createElement('video');
if(event.type === 'local') {
video.setAttribute('class', 'myvideo');
//$('.yourVideo').attr('src', event.stream);
//$('.yourVideo').attr('id', event.streamid);
//alert('local');
/*video.volume = 0;
try {
video.setAttributeNode(document.createAttribute('muted'));
} catch (e) {
video.setAttribute('muted', true);
}*/
}
if (event.type === 'remote') {
alert('remote');
video.setAttribute('class', 'othersvideo');
}
//video.src = URL.createObjectURL(event.stream);
setTimeout(function() {
var existing = document.getElementById(event.streamid);
if(existing && existing.parentNode) {
existing.parentNode.removeChild(existing);
}
event.mediaElement.removeAttribute('src');
event.mediaElement.removeAttribute('srcObject');
event.mediaElement.muted = true;
event.mediaElement.volume = 0;
try {
video.setAttributeNode(document.createAttribute('autoplay'));
video.setAttributeNode(document.createAttribute('playsinline'));
} catch (e) {
video.setAttribute('autoplay', true);
video.setAttribute('playsinline', true);
}
console.log(JSON.stringify(event));
video.srcObject = event.stream;
var width = parseInt(connection.videosContainer.clientWidth / 3) - 20;
var width = $(document).width();
var height = $(document).height();
var mediaElement = getHTMLMediaElement(video, {
/*title: event.userid,*/
buttons: ['full-screen'],
width: width,
showOnMouseEnter: false
});
connection.videosContainer.appendChild(mediaElement);
mediaElement.media.play();
var isInitiator = connection.isInitiator;
if (isInitiator === true && event.type === 'local') {
// initiator's own stream
alert('you are initiator');
}else{
alert('you are remote');
}
mediaElement.id = event.streamid;
//video.play();
}, 5000);
};
var recordingStatus = document.getElementById('recording-status');
var chkRecordConference = document.getElementById('record-entire-conference');
var btnStopRecording = document.getElementById('btn-stop-recording');
btnStopRecording.onclick = function() {
var recorder = connection.recorder;
if(!recorder) return alert('No recorder found.');
recorder.stopRecording(function() {
var blob = recorder.getBlob();
invokeSaveAsDialog(blob);
connection.recorder = null;
btnStopRecording.style.display = 'none';
recordingStatus.style.display = 'none';
chkRecordConference.parentNode.style.display = 'inline-block';
});
};
connection.onstreamended = function(event) {
var mediaElement = document.getElementById(event.streamid);
if (mediaElement) {
mediaElement.parentNode.removeChild(mediaElement);
}
};
connection.onMediaError = function(e) {
if (e.message === 'Concurrent mic process limit.') {
if (DetectRTC.audioInputDevices.length <= 1) {
alert('Please select external microphone. Check github issue number 483.');
return;
}
var secondaryMic = DetectRTC.audioInputDevices[1].deviceId;
connection.mediaConstraints.audio = {
deviceId: secondaryMic
};
connection.join(connection.sessionid);
}
};
// ..................................
// ALL below scripts are redundant!!!
// ..................................
function disableInputButtons(enable) {
document.getElementById('room-id').onkeyup();
document.getElementById('open-or-join-room').disabled = !enable;
document.getElementById('open-room').disabled = !enable;
document.getElementById('join-room').disabled = !enable;
document.getElementById('room-id').disabled = !enable;
}
// ......................................................
// ......................Handling Room-ID................
// ......................................................
function showRoomURL(roomid) {
var roomHashURL = '#' + roomid;
var roomQueryStringURL = '?roomid=' + roomid;
var html = '<h2>Unique URL for your room:</h2><br>';
html += 'Hash URL: ' + roomHashURL + '';
html += '<br>';
html += 'QueryString URL: ' + roomQueryStringURL + '';
var roomURLsDiv = document.getElementById('room-urls');
roomURLsDiv.innerHTML = html;
roomURLsDiv.style.display = 'block';
}
(function() {
var params = {},
r = /([^&=]+)=?([^&]*)/g;
function d(s) {
return decodeURIComponent(s.replace(/\+/g, ' '));
}
var match, search = window.location.search;
while (match = r.exec(search.substring(1)))
params[d(match[1])] = d(match[2]);
window.params = params;
})();
var roomid = '';
if (localStorage.getItem(connection.socketMessageEvent)) {
roomid = localStorage.getItem(connection.socketMessageEvent);
} else {
roomid = connection.token();
}
var txtRoomId = document.getElementById('room-id');
txtRoomId.value = roomid;
txtRoomId.onkeyup = txtRoomId.oninput = txtRoomId.onpaste = function() {
localStorage.setItem(connection.socketMessageEvent, document.getElementById('room-id').value);
};
var hashString = location.hash.replace('#', '');
if (hashString.length && hashString.indexOf('comment-') == 0) {
hashString = '';
}
var roomid = params.roomid;
if (!roomid && hashString.length) {
roomid = hashString;
}
if (roomid && roomid.length) {
document.getElementById('room-id').value = roomid;
localStorage.setItem(connection.socketMessageEvent, roomid);
// auto-join-room
(function reCheckRoomPresence() {
connection.checkPresence(roomid, function(isRoomExist) {
if (isRoomExist) {
connection.join(roomid);
return;
}
setTimeout(reCheckRoomPresence, 5000);
});
})();
disableInputButtons();
}
// detect 2G
if(navigator.connection &&
navigator.connection.type === 'cellular' &&
navigator.connection.downlinkMax <= 0.115) {
alert('2G is not supported. Please use a better internet service.');
}
$(document).on('click', '.mybtn', function() {
window.cordova.InAppBrowser.open(" https://vps267717.ovh.net/webrtc", "_blank", "location=no,toolbar=yes");
});
HTML:
<!-- Demo version: 2019.01.09 -->
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Video Conferencing using RTCMultiConnection</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<script>
setTimeout(function() {
navigator.splashscreen.hide();
}, 4000);
// alert dialog dismissed
function alertDismissed() {
}
</script>
<link rel="stylesheet" href="https://rtcmulticonnection.herokuapp.com/demos/stylesheet.css">
<script src="https://rtcmulticonnection.herokuapp.com/demos/menu.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/dist/RTCMultiConnection.min.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/node_modules/webrtc-adapter/out/adapter.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/socket.io/socket.io.js"></script>
<!-- custom layout for HTML5 audio/video elements -->
<link rel="stylesheet" href="https://rtcmulticonnection.herokuapp.com/dev/getHTMLMediaElement.css">
<script src="https://rtcmulticonnection.herokuapp.com/dev/getHTMLMediaElement.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/node_modules/recordrtc/RecordRTC.js"></script>
<script src="cordova.js"></script>
<script src="ios-websocket-hack.js"></script>
<style>
/* .myvideo{
width:100px !important;
height:100px !important;
background:#ccc;
position:absolute;
top:0;
left:0;
z-index:10;
}
.othersvideo{
width:100% !important;
height:100% !important;
background:#ccc;
position:absolute;
top:0;
left:0;
z-index:0;
}*/
* {
word-wrap:break-word;
}
video {
object-fit: fill;
width: 30%;
}
button,
input,
select {
font-weight: normal;
padding: 2px 4px;
text-decoration: none;
display: inline-block;
text-shadow: none;
font-size: 16px;
outline: none;
}
.make-center {
text-align: center;
padding: 5px 10px;
}
img, input, textarea {
max-width: 100%
}
#media all and (max-width: 500px) {
.fork-left, .fork-right, .github-stargazers {
display: none;
}
}
</style>
</head>
<body>
<button class="mybtn" >click me now</button>
<section class="make-center">
<div>
<label><input type="checkbox" id="record-entire-conference"> Record Entire Conference In The Browser?</label>
<span id="recording-status" style="display: none;"></span>
<button id="btn-stop-recording" style="display: none;">Stop Recording</button>
<br><br>
<input type="text" id="room-id" value="abcdef" autocorrect=off autocapitalize=off size=20>
<button id="open-room">Open Room</button>
<button id="join-room">Join Room</button>
<button id="open-or-join-room">Auto Open Or Join Room</button>
</div>
<div id="videos-container" style="margin: 20px 0;"></div>
<div id="room-urls" style="text-align: center;display: none;background: #F1EDED;margin: 15px -10px;border: 1px solid rgb(189, 189, 189);border-left: 0;border-right: 0;"></div>
</section>
<script src="https://cdn.webrtc-experiment.com/common.js"></script>
</body>
</html>
Any help would be greately appreciated.
Thanks in advance.

Make 2 counters with different storage

I am going to make more so just need help with how to make them different counters, i tired google and some html documents but didn't find the way to do it.
function clickCounter() {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "Sälj " + localStorage.clickcount + " st.";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
function clickCounter(b) {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcountr) {
localStorage.clickcountr = Number(localStorage.clickcountr) + 1;
} else {
localStorage.clickcountr = 2;
}
document.getElementById("resultr").innerHTML = "Annu " + localStorage.clickcountr + " st.";
} else {
document.getElementById("resultr").innerHTML = "Sorry, your browser does not support web storage...";
}
}
<p><button onclick="clickCounter()" type="button">Sälj!</button></p>
<div id="result"></div>
<p><button onclick="clickCounter(b)" type="button">Annu!</button></p>
<div id="resultr"></div>
--Sälj = first counter
--Annu = second counter
The problem is that you named your functions in the same way. Because of this, the second function overwrites the first one, and as result, both functions are calling the same function.
Usually you do not need to write two different functions that do the same thing. In your case, your JavaScript function should look something like this:
function clickCounter(id, label) {
var node = document.getElementById(id);
if (!node) {
return console.error('Element #' + id + ' not found');
}
if (window.localStorage === undefined) {
node.innerHTML = 'Sorry, your browser does not support web storage...';
} else {
var key = 'clickcount_' + id;
localStorage[key] = (++localStorage[key] || 1);
node.innerHTML = label + ' ' + localStorage[key] + ' st.';
}
}
And your buttons:
<p><button onclick="clickCounter('result', this.innerHTML)" type="button">Sälj!</button></p>
<div id="result"></div>
<p><button onclick="clickCounter('resultr', this.innerHTML)" type="button">Annu!</button></p>
<div id="resultr"></div>

Phonegap App not Running javascript elements

So I have a code that runs the css and html fine in phonegap, but the javascript items do not function. For example I'm making a To Do app, but the button will not save my new item, or click to delete.
css code
body
{
font-family: Verdana, Arial;
font-size: 18px;
background-color:#D4D0B4;
}
h1
{
background-color:#626b5e;
font-size:1em;
color:#F5F6F5;
line-height:2em;
text-align:center;
}
#newTaskInput, #addNewTask
{
display:block;
width:98%;
margin-top:5px;
margin-left:auto;
margin-right:auto;
background-color:#757769;
border:0;
height;2em;
font-size:1em;
color:#F5F6F5;
}
#taskList
{
margin-top:10px;
}
#taskList > li
{
background: -webkit-linear-gradient(#FFF, #F6F6F7);
background: -o-linear-gradient(#FFF, #F6F6F7);
background: -moz-linear-gradient(#FFF, #F6F6F7);
background: linear-gradient(#FFF, #F6F6F7);
border:1px solid #BBB6AF
line-height:2em;
color:#929292;
margin-top:2px;
}
#taskList span
{
margin-left:5px;
}
.done
{
text-decoration:line-through;
opacity:0.5;
}
HTML
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="type/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Todo List</title>
</head>
<body>
<h1>Todo List</h1>
<div id="newTaskSection">
<input type="text" id="newTaskInput" placeholder="New Task">
<button id="addNewTask">Add</button>
</div>
<ul id="taskList">
</ul>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
javascript
var taskList = new Array();
$( document ).ready(function(){
var $newTaskInput = $('#newTaskInput');
var $taskList = $('#taskList');
var taskTouchStart;
var taskTouchEnd;
var taskTouchStartX;
var taskTouchEndX;
if( window.localStorage )
{
taskList = JSON.parse(window.localStorage.getItem('taskList'));
}
if(null !== taskList)
{
for(i=0;i<taskList.length;i++)
{
var newTask = '<li data-key="' + taskList[1].key + '"><span>' + taskList[i].task + '</span></li>';
$taskList.append(newTask);
}
}
else
{
taskList = new Array();
}
$('#addNewTask').on('click', function(){
var key = Date.now();
var newTask = '<li data-key="' + key + '"><span>' + $newTaskInput.val() + '</span></li>';
$taskList.append( newTask );
taskList.push({key:key, task:$newTaskInput.val(), done:false});
if(window.localStorage)
{
window.localStorage.setItem('taskList', JSON.stringify(taskList));
}
$newTaskInput.val('');
});
$taskList.on('touchstart', 'li', function(e){
var start = document.elementFromPoint( e.originalEvent.touches[0].pageX, e.originalEvent.touches[0].pageY);
taskTouchStart = $(start).attr('data-key');
taskTouchStartX = e.originalEvent.touches[0].pageX;
});
$taskList.on('touchend', 'li', function(e){
var $end;
var $this = $(this);
var end = document.elementFromPoint( e.originalEvent.touches[0].pageX, e.originalEvent.touches[0].pageY);
$end = $(end);
taskTouchEnd = $end.attr('data-key');
taskTouchEndX = e.originalEvent.touches[0].pageX;
if(taskTouchStart == taskTouchEnd)
{
if(taskTouchStartX < taskTouchEndX)
{
if($this.hasClass('done'))
{
$this.removeClass('done');
}
else
{
$this.addClass('done');
}
}
else
{
taskList = $.grep(taskList, function(e){ return e.key != taskTouchEnd;});
if(window.localStorage)
{
window.localStorage.setItem('taskList', JSON.stringify(taskList));
}
$end.remove();
}
}
});
});
Simplified form of the done/not done handler in the code below, which would replace your current on('touchstart.. and on('touchend... blocks and remove a lot of complexity:
Additionally, you have a 1 where there should be an i in your display block (unless I mistook the purpose), and you're not setting the done class for tasks from localStorage which are marked such.
Changes commented in the code below, which would replace the JS you posed above.
Also, apologies, but I've mixed jQuery and vanilla JS, and only went so far as to get a working example, you'll have to work further on validation on what not, hopefully this gets you going.
$( document ).ready(function(){
var $newTaskInput = $('#newTaskInput');
var $taskList = $('#taskList');
if( window.localStorage ){
taskList = JSON.parse(window.localStorage.getItem('taskList'));
}
if(null !== taskList){
for(i=0;i<taskList.length;i++){
// Should we add the 'done' class to these items?
var newTaskClass = (taskList[i].done)? 'done': '';
// taskList[1].key to taskList[i].key ??? or am I missing something?
var newTask = '<li data-key="' + taskList[i].key + '" class="' + newTaskClass + '"><span>' + taskList[i].task + '</span></li>';
$taskList.append(newTask);
}
}
else {
taskList = new Array();
}
$('#addNewTask').on('click', function(){
var key = Date.now();
var newTask = '<li data-key="' + key + '"><span>' + $newTaskInput.val() + '</span></li>';
$taskList.append( newTask );
taskList.push({key:key, task:$newTaskInput.val(), done:false});
if(window.localStorage)
{
window.localStorage.setItem('taskList', JSON.stringify(taskList));
}
$newTaskInput.val('');
});
// Replaces the 'touchstart/end' handlers
$(document).on('click', '#taskList li', function(e){
var task = $(this);
// Update the li class
if (task.hasClass('done')){
task.removeClass('done');
} else {
task.addClass('done');
}
// Find the item by its key property (assumes key exists / no duplicates)
var itemToUpdate = taskList.filter(function(item){
return item.key === task.data('key');
})[0];
// If true, make false, if false, make ture
itemToUpdate.done = !itemToUpdate.done;
// Over-write the task list in local storage
window.localStorage.setItem('taskList', JSON.stringify(taskList));
});
});

Found this nasty code, I wonder what it does? Should I be worried...?

I have recently saw some free file downloading website on server log, and in in one of the site's source code had some suspicious javascript code. Should I be worried about it? as they might have run or may have installed spam inside one of our company's computer,
Code
<script type="text/javascript">
var stamp = "0529e8679c27247e794a";
var file = "74109";
var host = "fileice.net";
var _0x6675 = ["\x64\x69\x76\x2E\x6D\x65\x6E\x75\x20\x6C\x69", "\x68\x34", "\x68\x33", "\x68\x32", "\x68\x31", "\x72\x65\x70\x6C\x61\x63\x65", "\x6F\x6E\x6C\x6F\x61\x64", "\x6C\x6F\x63\x61\x74\x69\x6F\x6E", "\x70\x61\x72\x65\x6E\x74", "\x68\x74\x74\x70\x3A\x2F\x2F", "\x2F\x64\x6F\x77\x6E\x6C\x6F\x61\x64\x2E\x70\x68\x70\x3F\x66\x69\x6C\x65\x3D", "", "\x67\x65\x74\x45\x6C\x65\x6D\x65\x6E\x74\x42\x79\x49\x64", "\x69\x6E\x6E\x65\x72\x48\x54\x4D\x4C", "\x64\x65\x73\x63", "\x3C\x70\x3E\x54\x68\x65\x20\x64\x6F\x77\x6E\x6C\x6F\x61\x64\x20\x77\x69\x6C\x6C\x20\x61\x75\x74\x6F\x6D\x61\x74\x69\x63\x61\x6C\x6C\x79\x20\x62\x65\x67\x69\x6E\x20\x77\x68\x65\x6E\x20\x79\x6F\x75\x20\x73\x75\x63\x63\x65\x73\x73\x66\x75\x6C\x6C\x79\x20\x66\x69\x6E\x69\x73\x68\x20\x74\x68\x65\x20\x73\x75\x72\x76\x65\x79\x20\x79\x6F\x75\x20\x68\x61\x76\x65\x20\x63\x68\x6F\x73\x65\x6E\x2E\x20\x49\x66\x20\x74\x68\x65\x20\x66\x69\x6C\x65\x20\x64\x6F\x65\x73\x20\x6E\x6F\x74\x20\x61\x75\x74\x6F\x6D\x61\x74\x69\x63\x61\x6C\x6C\x79\x20\x75\x6E\x6C\x6F\x63\x6B\x20\x61\x66\x74\x65\x72\x20\x61\x20\x6D\x69\x6E\x75\x74\x65\x2C\x20\x70\x6C\x65\x61\x73\x65\x20\x63\x68\x6F\x6F\x73\x65\x20\x61\x6E\x6F\x74\x68\x65\x72\x20\x73\x75\x72\x76\x65\x79\x20\x61\x6E\x64\x20\x63\x6F\x6D\x70\x6C\x65\x74\x65\x20\x69\x74\x2E\x3C\x2F\x70\x3E", "\x64\x69\x73\x70\x6C\x61\x79", "\x73\x74\x79\x6C\x65", "\x6C\x6F\x61\x64\x69\x6E\x67\x69\x6D\x67", "\x62\x6C\x6F\x63\x6B", "\x73\x72\x63", "\x6F\x66\x66\x65\x72\x63\x68\x65\x63\x6B", "\x6F\x66\x66\x65\x72\x63\x68\x65\x63\x6B\x2E\x70\x68\x70\x3F\x66\x69\x6C\x65\x3D", "\x26\x74\x3D", "\x73\x70\x63\x6E\x67", "\x26\x61\x6A\x61\x78", "\x31", "\x3C\x70\x3E\x59\x6F\x75\x72\x20\x66\x69\x6C\x65\x20\x68\x61\x73\x20\x62\x65\x65\x6E\x20\x75\x6E\x6C\x6F\x63\x6B\x65\x64\x21\x20\x43\x6C\x69\x63\x6B\x20\x6F\x6B\x61\x79\x20\x6F\x6E\x20\x74\x68\x65\x20\x64\x6F\x77\x6E\x6C\x6F\x61\x64\x20\x70\x72\x6F\x6D\x70\x74\x20\x74\x6F\x20\x64\x6F\x77\x6E\x6C\x6F\x61\x64\x20\x74\x68\x65\x20\x66\x69\x6C\x65\x2E\x3C\x2F\x70\x3E", "\x6E\x6F\x6E\x65", "\x3C\x62\x72\x2F\x3E\x3C\x62\x72\x2F\x3E", "\x70\x6F\x73\x74", "\x69\x6E\x66\x6F", "\x3C\x64\x69\x76\x20\x73\x74\x79\x6C\x65\x3D\x22\x70\x61\x64\x64\x69\x6E\x67\x3A\x20\x35\x70\x78\x20\x37\x70\x78\x3B\x20\x62\x6F\x72\x64\x65\x72\x3A\x20\x31\x70\x78\x20\x73\x6F\x6C\x69\x64\x20\x23\x65\x32\x65\x32\x65\x32\x3B\x20\x76\x65\x72\x74\x69\x63\x61\x6C\x2D\x61\x6C\x69\x67\x6E\x3A\x20\x6D\x69\x64\x64\x6C\x65\x3B\x20\x62\x61\x63\x6B\x67\x72\x6F\x75\x6E\x64\x2D\x63\x6F\x6C\x6F\x72\x3A\x20\x23\x46\x37\x46\x37\x46\x37\x3B\x20\x77\x69\x64\x74\x68\x3A\x20\x37\x33\x25\x3B\x22\x3E\x3C\x70\x3E", "\x3C\x2F\x70\x3E\x3C\x2F\x64\x69\x76\x3E"];
Cufon[_0x6675[5]](_0x6675[4])(_0x6675[3])(_0x6675[2])(_0x6675[1])(_0x6675[0]);
var prev = _0x6675[11];
function _(_0x2391x4) {
return document[_0x6675[12]](_0x2391x4)
};
function launch() {
var _0x2391x6 = 0;
_(_0x6675[14])[_0x6675[13]] = _0x6675[15];
_(_0x6675[18])[_0x6675[17]][_0x6675[16]] = _0x6675[19];
_(_0x6675[21])[_0x6675[20]] = _0x6675[22] + file + _0x6675[23] + stamp;
prev = curr;
_(_0x6675[24])[_0x6675[13]] = _0x6675[11];
setInterval(function () {
if (_0x2391x6 == 0) {
$[_0x6675[30]](_0x6675[22] + file + _0x6675[25], function (_0x2391x7) {
if (_0x2391x7 == _0x6675[26]) {
_(_0x6675[14])[_0x6675[13]] = _0x6675[27];
_(_0x6675[18])[_0x6675[17]][_0x6675[16]] = _0x6675[28];
_(_0x6675[21])[_0x6675[20]] = _0x6675[11];
_(_0x6675[21])[_0x6675[20]] = _0x6675[22] + file + _0x6675[23] + stamp;
_0x2391x6 = 1;
prev = _0x6675[11];
clearinfo();
_(_0x6675[24])[_0x6675[13]] = _0x6675[29]
}
})
} else {
clearInterval()
}
}, 10000)
};
function showinfo(_0x2391x9) {
prev = _(_0x6675[31])[_0x6675[13]];
_(_0x6675[31])[_0x6675[13]] = _0x6675[32] + _0x2391x9 + _0x6675[33];
curr = _(_0x6675[31])[_0x6675[13]]
};
function clearinfo() {
_(_0x6675[31])[_0x6675[13]] = prev
};
</script>
URL
http:\\www.fileice.net/download.php?t=regular&file=rfve
Decrypting the _0x6675 array yields:
["div.menu li","h4","h3","h2","h1","replace","onload","location","parent","http://","/download.php?file=","","getElementById","innerHTML","desc","<p>The download will automatically begin when you successfully finish the survey you have chosen. If the file does not automatically unlock after a minute, please choose another survey and complete it.</p>","display","style","loadingimg","block","src","offercheck","offercheck.php?file=","&t=","spcng","&ajax","1","<p>Your file has been unlocked! Click okay on the download prompt to download the file.</p>","none","<br/><br/>","post","info","<div style=\"padding: 5px 7px; border: 1px solid #e2e2e2; vertical-align: middle; background-color: #F7F7F7; width: 73%;\"><p>","</p></div>"]
Nothing too spectacular in my opinion.
Looks like just some obfuscated JavaScript code to prevent copying their scripts.
You are hosting code and you don't know where it came from?
Yes. Be worried.
Pull the server offline and security audit it.
<script type="text/javascript">
var stamp = "9bdcac6591542d17c8ff";
var file = "126640";
var host = "fileice.net";
var prev = "";
// see: https://github.com/sorccu/cufon/wiki/API
Cufon.replace("h1")("h2")("h3")("h4")("div.menu li");
window.onload = function () {
// Make sure page is in a frame
if (window.location == window.parent.location) {
window.location = "http://" + host + "/download.php?file=" + file;
}
}
function _(id) {
return document.getElementById(id);
}
function launch() {
var offerFinished = 0;
_("desc").innerHTML. = "<p>The download will automatically begin when you successfully finish the survey you have chosen. If the file does not automatically unlock after a minute, please choose another survey and complete it.</p>";
_("loadingimg").style.display = "block";
_("offercheck").src = "offercheck.php?file=" + file + "&t=" + stamp;
_("spcng").innerHTML = "";
prev = curr;
setInterval(function () {
if (offerFinished == 0) {
// JQuery Ajax POST request
$.post("offercheck.php?file=" + file + "&ajax", function (data) {
if (data == "0") {
_("desc")["innerHTML"] = "<p>Your file has been unlocked! Click okay on the download prompt to download the file.</p>";
_("loadingimg").style.display = "none";
_("offercheck").src = "";
_("offercheck").src = "offercheck.php?file=" + file + "&t=" + stamp;
_("spcng").innerHTML = "<br/><br/>";
offerFinished = 1;
prev = "";
clearinfo();
}
})
} else {
clearInterval()
}
}, 10000)
};
function showinfo(info) {
prev = _("info").innerHTML;
_("info").innerHTML = "<div style=\"padding: 5px 7px; border: 1px solid #e2e2e2; vertical-align: middle; background-color: #F7F7F7; width: 73%;\"><p>" + info + "</p></div>";
curr = _("info").innerHTML;
}
function clearinfo() {
_("info").innerHTML = prev;
}
</script>
Just paste the text of your code into the cell and hit the 'decode' button here (not a promo for this site, nor do I own it etc)> http://ddecode.com/hexdecoder/

Categories