PouchDB IE11 using file:// - javascript

I'm trying to get PouchDB's Getting Started Guide working using IE11 from a local file (file://). Is it possible?
It works great using a local http server by adding the following scripts to the header in the index.html file:
<script src="https://cdn.jsdelivr.net/npm/promise-polyfill#8/dist/polyfill.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/whatwg-fetch#3.0.0/dist/fetch.umd.min.js"></script>
I think my issue is both indexedDB and localStorage seem to be restricted by IE when served using the file:// protocol, however I was able to get localStorage working on it's own using the code below from this post:
!localStorage && (l = location, p = l.pathname.replace(/(^..)(:)/, "$1$$"), (l.href = l.protocol + "//127.0.0.1" + p));
So I thought that would get it working, but even then when i add the pouchdb localstorage adapter I get this error: "AssertionError: .status required, old abstract-leveldown".
Even if that did work, the solution isn't ideal because I need to add file://127.0.0.1 to the trusted sites list.
That's about as far as I've gotten, any help would be appreciated!

Thanks to Zhi Lv - MSFT comment I was able to get the demo working in IE11, however it requires the user to add 'file://127.0.0.1' to the trusted sites list in IE.
After completing the 'Getting Started' guide you'll need to make the following changes.
Update the head element in index.html file:
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>VanillaJS • TodoMVC</title>
<link rel="stylesheet" href="style/base.css">
<script src="https://cdn.jsdelivr.net/npm/promise-polyfill#8/dist/polyfill.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/whatwg-fetch#3.0.0/dist/fetch.umd.min.js"></script>
<script src="pouchdb/object-assign.js"></script>
<script src="pouchdb/pouchdb-7.2.1.js"></script>
<script src="pouchdb/pouchdb.localstorage.js"></script>
<script src="pouchdb/pouchdb.memory.js"></script>
<!--[if IE]>
<script src="style/ie.js"></script>
<![endif]-->
</head>
You will need to download any missing 7.2.1 pouch-db files and put into a pouchdb directory. object-assign.js can be found here.
Modify the app.js, replace the db variable with these two lines:
!localStorage && (l = location, p = l.pathname.replace(/(^..)(:)/, "$1$$"), (l.href = l.protocol + "//127.0.0.1" + p));
var db = new PouchDB('todos', {adapter: 'localstorage'});
Goto line 8796 of pouchdb.localstorage.js, edit it to set the db.status like this:
function LevelUP (db, options, callback) {
db.status = 'unknown';
if (!(this instanceof LevelUP)) {
return new LevelUP(db, options, callback)
}
Bit of a muck around, but worked for me. Any improvement please let me know.

Related

Inline Scripting issue in windows 10 apps with Microsoft edge

Im developing Windows 10 store apps Javascript/Html and since there is Microsoft EDGE in apps as the browser, inline scripting no longer works. If i put the code in an external file, the page loads, but none of the click events work. Is there any solution for this. Small example where onclick attribute does not work.
Code
default.html 7 default.js
// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
function gored() {
document.body.style.backgroundColor = red;
}
(function () {
"use strict";
WinJS.Binding.optimizeBindingReferences = true;
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var isFromBackground = false;
app.onactivated = function (args) {
var localSettings = Windows.Storage.ApplicationData.current.localSettings;
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
// TODO: This application has been newly launched. Initialize
// your application here.
} else {
// TODO: This application has been reactivated from suspension.
// Restore application state here.
}
args.setPromise(WinJS.UI.processAll());
}
};
app.oncheckpoint = function (args) {
// TODO: This application is about to be suspended. Save any state
// that needs to persist across suspensions here. You might use the
// WinJS.Application.sessionState object, which is automatically
// saved and restored across suspension. If you need to complete an
// asynchronous operation before your application is suspended, call
// args.setPromise().
isFromBackground = true;
};
app.start();
})();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>App1</title>
<!-- WinJS references -->
<!-- To get the latest version of WinJS, go to: http://go.microsoft.com/fwlink/?LinkId=533245 -->
<link href="WinJS/css/ui-dark.css" rel="stylesheet" />
<script src="WinJS/js/WinJS.js"></script>
<!-- App1 references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
</head>
<body>
<p>Content goes here</p>
<button onclick="gored()"> Click Me</button>
</body>
</html>
I went into detail about this in a blog post.
Windows HTML5 apps have a strict security setting, especially when it comes to injecting code at runtime via JavaScript. I ran into this issue before as well.
You can wrap the function that you are using to inject the Javascript with another function, MSApp.execUnsafeLocalFunction().
When attempting to dynamically insert a div, Windows 8 throws an error. Specifically, it’s when trying to use something like:
div.innerHTML = "A string of some stuff"
HTML1701: Unable to add dynamic content ' a' A script attempted to inject dynamic content, or elements previously modified dynamically, that might be unsafe. For example, using the innerHTML property to add script or malformed HTML will generate this exception. Use the toStaticHTML method to filter dynamic content, or explicitly create elements and attributes with a method such as createElement. For more information, see http://go.microsoft.com/fwlink/?LinkID=
Reason:
The reasoning behind all of these problems is the same, so I’ll just state it here once for the sake of brevity. `Microsoft fears that the string can be intercepted somewhere along the line, and malicious content can be added to the values of your string.
Work Around:
The big issue with this method is that you’re trying to use innerHtml. Instead, use .append.
That still won’t work if you just try to pass in a string, however. What you need to do is set your string to a variable, then pass in that variable. If you do not create an object (that is, setting the string to a variable) then this will not work. If you just try to use a string, then you’ll see nothing but text where the div should be.
Here’s a single line example:
$panel.append('<'img src="' + item.thumbImageUrl +'" >');
If you try to pass that in, Windows 8 will throw the error seen above. Even if I wrap that in MSApp.execUnsafeLocalFunction() I will still see an error.
The workaround is as follow:
var appendString = '<'img src="' + item.thumbImageUrl '" >';
$panel.append(appendString);
Because I’m now taking that string and setting it to a variable (thereby turning it into an object), Windows 8 will allow me to pass in that object and create dynamic content.
Even then, it will occasionally throw the error above. HOWEVER, if you were to wrap that object in MSApp.execUnsafeLocalFunction(), you would then be in the clear. WinJS offers a function to wrap your own functions in, which allows you to basically say “I take responsibility for this function, and I assure you it’s safe.” That function is called: MSApp.execUnsafeLocalFunction().
So the final solution looks like this:
var appendString = '<'img src="' + item.thumbImageUrl '" >';
MSApp.execUnsafeLocalFunction(function() {
$panel.append(appendString);
});
You can read more about this issue here.
Further Reading:
execUnsafeLocalFunction from MSDN
TutsPlus tutorial on jQuery and Win8
I had a similar problem and found that a script read in the header did not work but when I moved it to the body, it did:
WORKS ON MOST BUT NOT ALL PAGES WITH 'EDGE'. WORKS WITH ALL PAGES ON ALL OTHER BROWSERS:
LT script type="text/javascript" src="../ie5.js" GT LT /script GT
LT script type="text/javascript" src="../common_functions.js" GT LT /script GT
LT /head GT
LT body GT
WORKS ON ALL PAGES WITH 'EDGE' AND OTHER BROWSERS:
LT /head GT
LT body GT
LT script type="text/javascript" src="../ie5.js" GT LT /script GT
LT script type="text/javascript" src="../common_functions.js" GT LT /script GT
Why? Only Microsoft will know.

Options to store data on desktop, using webpage

Goal:
To sum it up, I'm trying to replace an excel spreadsheet. I'm creating an application that will run in IE9, but does not connect to the internet or an intranet (I know, I know. Just bear with me. If you're curious read more below). It needs to use CRUD (create, read, update, and delete) methods on a set of data that changes daily. The dataset must persist even when the browser is closed.
Question:
What options are available, using javascript and html, for storing data on the local computer the web page is accessed on? I'm doing this at work, so there will be no server-side to this. I also will not be able to install any software on the computer, although I can download javascript plugins. The webpage will be loaded from a file on the computer, using Win 7 and IE9.
Background:
This deserves an explanation. I use an excel spreadsheet to track a set of data that changes daily. I'm learning HTML and javascript, and I can create a much better (and easier to use) solution as a webpage. I can create the UI / UX, but I'm having a difficult time figuring out how to store the data on the local computer. Any good suggestions?
Attempts:
Unfortunately, it seems localStorage is not an option. I'm attempting to use jStorage, but I've been running into problems there, also. A similar set of problems has been encountered using simpleStorage.
Thank you for considering, please let me know if any more info is needed, or if I need to clarify something.
Addendum:
Localstorage, and other forms of HTML5 storage, do not work. Officially it does, unofficially it is very buggy. See blog post here, and SO answer here. Either way, with the following simple code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Backlog Tracker</title>
<script src="jquery-2.1.1.min.js"></script>
<script src="backlog_localstorage.js"></script>
</head>
<body>
</body>
</html>
and javascript (ref as "backlog_localstorage.js" above):
$(document).ready(function(){
$("body").append("<button>Try It</button>");
$("button").click(function(){
localStorage.setItem("key1", "Hello");
console.log(localStorage.getItem("key1"));
});
});
... I get the following error: "SCRIPT5007: Unable to get value of the property 'setItem': object is null or undefined" on the line localStorage.setItem("key1", "Hello");
HTA (which is really just an html file with one extra tag and a different file extension) is one possible solution for windows users:
Important: Save as demo.hta to run on windows as an app
<!DOCTYPE html>
<html> <!-- some parts lifted from
http://msdn.microsoft.com/en-us/library/ms536496(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/ms536473(v=vs.85).aspx
-->
<head>
<title>State Saving Demo</title>
<hta:application id="App"
application="yes"
applicationname="demo"
icon="calc.exe"
border="thin"
caption="yes"
sysmenu="yes"
showintaskbar="yes"
singleinstance="yes"
sysmenu="no"
maximizeButton="yes"
minimizeButton="yes"
navigable="no"
scroll="yes"
contextmenu="no"
selection="no"
windowstate="normal" >
<!-- Use Internet Explorer 10 Standards mode (to use JSON, CSS3, etc...) -->
<meta http-equiv="x-ua-compatible" content="IE=10">
</head>
<body onload=loadMe() >
<h1 id=h1>Command-line args: </h1>
<h3>Persisted Text</h3>
<textarea rows=20 cols=100 id=mydata onchange=saveMe() >
You can change me and i won't forget!
</textarea>
<script>
document.title+=" - Today is " + Date(); // task/title bar demo
h1.innerHTML+= JSON.stringify( App.commandLine ); // optional invocation info here (much like a real app)
// app-specific custom code:
FILENAME="state.txt";
function saveMe(){save(FILENAME, mydata.value); }
function loadMe(){mydata.value=load(FILENAME) || mydata.value;}
// generic utils:
function load(filename) { //IE FSO file Loader
var file,
text="",
fso= new ActiveXObject('Scripting.FileSystemObject');
try{
file = fso.OpenTextFile(filename, 1, false);
text = file.readAll();
file.Close();
}catch(y){}
return text;
}
function save(filename, sData){ //IE FSO file Saver
var file,
fso = new ActiveXObject('Scripting.FileSystemObject');
file = fso.CreateTextFile(filename, 2, false);
file.write(sData);
file.Close();
return file;
}
</script>
</body>
</html>
I recently re-discovered HTAs, and they are not half bad. I don't think I would want to distribute and maintain them, but HTA's are an easy way to make simple desktop app using HTML, CSS, and JS. Its nice not to have to build anything to "recompile" the app after changes are made. saves a few steps compared to node-webkit, packaged apps, air, cordova, etc, but HTA's have a major downside: they only work on windows afaik...
Looks to me like you can use LocalStorage, the big question is how are you trying to store it? You can easily store an object/array into LocalStorage, and that object/array can be your data, then JS can output this into a table. If you're looking to store actual files then you're looking at something more like an ActiveX plugin.
http://caniuse.com/#search=localstorage
Alternatively if you have internet access through a desktop or a phone you can put this on Google Drive. This would be far easier than reinventing the wheel.

Update application cache

I wanted to make my site work offline and I did it. But the problem is that I can't update my manifest file. I have the function that should check for update and update it if is possible but I don't know why it's not working.
This is my index.html
<html manifest="VideoPlayer.appcache" >
<head>
<title>Video Player</title>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body id='main'>
...
<script>
window.addEventListener('load', function(e) {
window.applicationCache.addEventListener('updateready', function(e) {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
window.applicationCache.swapCache();
if (confirm('A new version of this site is available. Load it?')) {
window.location.reload();
}
} else {}
}, false);
}, false);
....
</script>
</body>
</html>
And my VideoPlayer.appcache:
CACHE MANIFEST
index.html
style.css
http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
Can You tell me what's wrong with it?
I don't know whether your Javascript can make it easier (I sure hope so!), but what I have learned from experiments with appcached files is that they are only successfully updated/refreshed/reloaded in Chrome and Firefox under the following conditions:
The in your case VideoPlayer.appcache file itself must also be updated. You can do that by including a date and time in the file and change that to the date and time that you update the web page. See the below code block how to include date and time.
Chrome's normal but total browser cache must be cleared as well; just doing a 'hard reload' with Ctrl + F5 won't do. See here how to clear it: http://www.guidingtech.com/1662/clearing-cache-in-google-chrome/.
In Firefox, that doesn't even do, not even in combination with Ctrl + F5. Firefox's Offline Cache must be cleared: Tools -> Options -> Advanced -> Network -> Offline Web Content and User Data -> Remove [site].
Here is the date and time method for the appcache file:
CACHE MANIFEST
# 2014-06-25 — 15.50
CACHE:
[your to-appcache files here]
Changing the date and/or time will tell the browser that the to-appcache file is updated and should be reloaded.
I have not tested matters in IE, among others things because I don't have IE10, and IE9 doesn't do appcaches.
Let me know how it works out if you will, especially in combination with your Javascript.

netbeans 7.4 inline js code formatting and auto completion

When any JS is embedded within HTML or PHP pages, Netbeans doesn't highlight the syntax and doesn't provide auto completion.
The sample code is as below:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Steps Template</title>
<script type="text/javascript" src="js/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui.min.js"></script>
<script type="text/javascript" src="js/initializer.js"></script>
<script type="text/javascript" src="js/database.js"></script>
</head>
<body>
<div id="bg">
<div id="mediaMini" style="">
<div id="bgBlock" style="opacity:0;"></div>
</div>
</div>
<script type="text/javascript">
$(function() {
var options = {
'imgPath': 'images',
'audioPath': 'audio'
};
$(document).ready(function() {
function preloadAllImages() {
var imagesLoaded = 0;
var images2PreLoad = new Array();
for (var i in universalStepsData) {
images2PreLoad.push(options.imgPath + '/' + (universalStepsData[i].imageSrc));
}
var loading = function loadAllImages(callback) {
var img = new Image();
img.src = images2PreLoad[imagesLoaded];
$(img).load(function() {
imagesLoaded++;
if (imagesLoaded == images2PreLoad.length) {
initialise('bgBlock', options);
}
else
loadAllImages(callback);
});
};
loading();
}
preloadAllImages();
});
});
</script>
</body>
My netbeans about page shows the following information.
Product Version: NetBeans IDE 7.4 (Build 201310111528)
Updates: NetBeans IDE is updated to version NetBeans 7.4 Patch 2
Java: 1.7.0_51; Java HotSpot(TM) 64-Bit Server VM 24.51-b03
Runtime: Java(TM) SE Runtime Environment 1.7.0_51-b13
System: Windows 8 version 6.2 running on amd64; Cp1252; en_AU (nb)
User directory: C:\Users\Nisarg\AppData\Roaming\NetBeans\7.4
Cache directory: C:\Users\Nisarg\AppData\Local\NetBeans\Cache\7.4
As some users suggested I have also checked in Tools -> Options -> Miscellaneous -> Files and checked that fle extension JS has text/javascript associated with it.
I also made sure that netbeans is up to date and all the plugins are up to date as well.
How to solve this issue? How can I get formatting and auto completion back?
Sharing this for those who might be having the same problem. This doesn't provide solution but observations. (This was too big for a comment)
Well turns out no one could come up with a definite solution. I even opened a ticket in Bugzilla but no response from there either.
Well I was sharing the project with other guys and they were using netbeans 7.3 while I upgraded to 7.4. I believe this was a the problem where the conflict was occurring. Once I reverted back to 7.3 all was good.
Once version 8 was released, I upgraded to 8 while the other fellas were still at 7.3. Till now (touch wood) it hasn't caused any issues.
So in a nutshell, it seems like 7.4 and 7.3 might have internal conflict. Or might not but they both don't work together on same project at same time.

Uncaught ReferenceError when accessing an object from another JS file

I have various JS libraries in my web application, which are loaded before my main JS file (main.js). One of these libraries is jshashtable, but when I try to create a new Hashtable object in main.js, Google Chrome and Firefox throw a ReferenceError, complaining that the variable does not exist.
Here is the <head> of the application:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="/static/jquery-1.4.4.min.js"></script>
<script type="text/javacsript" src="/static/jshashtable-2.1.js"></script>
<script type="text/javascript" src="/static/main.js"></script>
Here is the problem line in main.js:
posts = new Hashtable();
This line is inside a function called init which is called when the page has finished loading (using the jquery $(document).ready() function).
Any reason why Hashtable is not global? Google maps and jquery objects work with no such problem. The source of jshashtable can be seen on Google code.
Updated answer: The problem is that you've got a typo in the script tag:
<script type="text/javacsript" src="/static/jshashtable-2.1.js"></script>
<!-- ^^---- here (the letters are transposed) -->
I couldn't understand why you would be running into a problem and decided to actually copy-and-paste your script tags and replicate the structure exactly on my machine. And things stopped working and my world tilted 3° counter-clockwise until I finally stared at them long enough to see it.
Provided that the jshashtable code really is at /static/jshashtable-2.1.js and your server is serving it up correctly (double-check on Chrome's resources tab in the dev tools), I can't see any reason for that. Your scripts are in the right order, and jshashtable's docs show using a global Hashtable (and the code link you gave clearly shows it creating one).
Edit: I've just replicated that same structure (same scripts, same order, using jQuery(document).ready(function() { ... });) on my own server, and am not having that problem. I can create a Hashtable and use its functions.
My HTML:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Test Page</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type='text/javascript' src='jquery-1.4.4.js'></script>
<script type='text/javascript' src='jshashtable-2.1.js'></script>
<script type='text/javascript' src='main.js'></script>
</head>
<body>
</body>
</html>
My main.js:
jQuery(document).ready(function() {
try {
var ht = new Hashtable();
display("typeof ht = " + typeof ht);
display("ht.size() = " + ht.size());
}
catch (e) {
display("Exception: " + e);
}
function display(msg)
{
$("<p>").html(msg).appendTo(document.body);
}
});
Only difference is I'm not using a /static prefix, and I'm absolutely certain that makes no difference.

Categories