Following is the content of my JSON File -
{
"tags": [
"Red",
"Green",
"Blue",
"Yellow"
]
}
I checked this with jsonlint but still I am getting the following error in firefox.
Timestamp: Wednesday 18 June 2014 10:39:41 IST Error: not well-formed
Source File:
file:///home/trialcode/trialcode/Projects/ang/18-06-2014/ang/content.json
Line: 1, Column: 1 Source Code: {
I am not sure what I am doing wrong if any.
FYI -
OS - Linux Ubuntu 12.04
Firefox - 24.0
EDIT
I am using the content of content.json file in angular controller via $http.get method.
I explored more about this kind of error and found it is related with the Content-Type setting.
Following is the full code -
<!doctype html>
<html lang="en" ng-app="app">
<head>
<title>JSON Read In Angularjs</title>
<meta charset="UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<script>
var app = angular.module('app', []);
app.controller('myCtrl', function($scope, $http){
$scope.data = {};
$http.get('content.json').success(function(data) {
$scope.data = data;
});
});
</script>
</head>
<body ng-controller="myCtrl">
<ul>
<li ng-repeat="em in data.tags">{{em}}</li>
</ul>
</body>
</html>
How do I set the content type if that is a problem. I searched HERE but unable to fix it. Help me Please if any.
After few hours of searching I came across that -
Chrome and other modern browsers have implemented security
restrictions for Cross Origin Requests, which means that you cannot
load anything through file:/// , you need to use http:// protocol at
all times, even locally -due Same Origin policies.
Source -
Cross Origin Script Stackoverflow Answer
Simple Solution For Local Cross Origin Requests
Related
Most browsers support 'import', so the following should work:
/**
* Adder.mjs
*/
class Adder {
add(n1, n2) {
return n1 + n2;
}
}
export default Adder;
test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Import Test</title>
<script type="module">
import Adder from "./Adder.mjs";
var adder = new Adder();
var result = adder.add(1, 1);
console.log("Result: " + result.toString());
</script>
</head>
<body>
</body>
</html>
It however results in the following error (Chromium debug console):
Access to script at 'file:///home/gso/eclipse-workspace/Test/Adder.js' from origin 'null' has been blocked by CORS policy: The response is invalid.
test.html:7 GET file:///home/gso/eclipse-workspace/Test/Adder.js net::ERR_FAILED
As connexo pointed out:
"Modules don't work over the file:// protocol. You need a webserver."
It's also worth noting that Apache does not support the .mjs file extension, ES6 modules have to be suffixed .js.
I am contemplating moving from Dart to ES6 but Chrome doesn't seem to support the new import statement which is critical to me.
I used the (named export) code from this site: http://www.2ality.com/2014/09/es6-modules-final.html
I tried it even with
<module import="main"><module>
I get the error: "Unexpected token import"
Any information if they will support it before the final release ?
code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>ES6</title>
</head>
<body bgcolor="blue">
<script type="module" src="main.js"></script>
</body>
</html>
main.js
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
lib.js:
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
It works now, finally in Chrome 60 with the Experimental Web Platform features enabled.
Here is a test:
https://github.com/paulirish/es-modules-todomvc
See here for status news:
https://www.chromestatus.com/features/5365692190687232
Safari Tech Review 19, via WebKit, now supports modules.
https://twitter.com/Constellation/status/806660783312543744
https://webkit.org/status/
I am learning angularjs and following tutorial from - here
Here is my index.jsp -
<!doctype html>
<html lang="en" ng-app="phoneCatApp">
<head>
<title>Angular Example</title>
<script type="text/javascript" src="angular/angular.min.js"></script>
<script type="text/javascript" src="app/js/controllers.js"></script>
</head>
<body ng-controller="phoneListCtrl">
Search : -
<input ng-model="query"/> Sort by:
<select ng-model="orderProp">
<option value="name">Alphabetical</option>
<option value="age">Newest</option>
<option value="-age">Oldest</option>
</select>
<p>Total number of phones: {{phones.length}}</p>
<ul>
<li ng-repeat="phone in phones | filter:query | orderBy:orderProp"><span>{{phone.name}}</span>
<p>{{phone.snippet}}</p></li>
</ul>
</body>
</html>
this version of controller.js works -
var phonecatApp = angular.module('phoneCatApp', []);
phonecatApp.controller('phoneListCtrlOld', function($scope) {
$scope.phones = [ {
'name' : 'Nexus S',
'snippet' : 'Fast just got faster with Nexus S.',
'age' : 1
}, {
'name' : 'Motorola XOOM™ with Wi-Fi',
'snippet' : 'The Next, Next Generation tablet.',
'age' : 2
}, {
'name' : 'MOTOROLA XOOM™',
'snippet' : 'The Next, Next Generation tablet.',
'age' : 3
} ];
$scope.orderProp = 'age';
});
but in the next step i tried fetching this json data with ajax call so controller look like this -
var phonecatApp = angular.module('phoneCatApp', []);
phonecatApp.controller('phoneListCtrl', function($scope, $http) {
$http.get('app/js/phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
});
But this gives me following error -
TypeError: dbg is undefined. debuggerLib.js (line 530)
I can see in firebug the ajax call is happening with code 304 Not Modified. and i can see data in response. but response content type is not json.
Please look into it and say what is the problem? Am i missing any js file to include or something else.
I have had this same error, and after some head scratching found a cause. I can't be sure whether this is your same cause.
Restarting Firefox, rebooting the PC, removing Firebug, reinstalling, optimizing, running registry clean, etc. -- nothing helped. I got error in debuggerLib.js line 556, dbg being undefined.
However, it turns out that I have installed Firebug back in the days, and it created a directory in my Roaming profile:
C:\Users\Leonardo\AppData\Roaming\Mozilla\Firefox\Profiles\Leonardo.Serni\firebug
In that directory there is a lot of JSON files, but none of them dated today, which is when I removed and reinstalled Firebug. So I wondered, "What if the new Firebug is loading something obsolete from this directory?".
I closed Firefox, renamed the directory from "firebug" to "bugfire", reopened Firefox.
Firebug is running perfectly and the error has disappeared. I had done the same thing without renaming the directory and the error did not disappear, so I'm confident that my hypothesis was correct.
The directory has been re-created, but there are now only two files in there - "annotations.json" and "breakpoints.json", both 0 bytes in size. Possibly some day I'll try adding the files from the old directory to see when the error comes back.
Update (thanks to DevNull's comment)
Possibly it is not necessary to nuke the whole directory. Verify that the annotations.json file is zero length. If it is not, just rename it to annotations.old while Firefox is not running.
I'm beginning to suspect that the dbg is actually debugging Firebug itself, and we do not have it defined because we aren't Firebug developers. It has nothing to do with the Firebug debugger that debugs our scripts.
You're probably using FireFox with firebug activated.
Turn off firebug and your issue will go away.
I had the same problem, other browsers had no issue and the console showed the error coming from debuggerLib.js (line 556). Deactivating it removed the error and allowed my application to run as expected.
use this code html head tag.
<base href="/">
....
Try this,
First initialize JSON array value is an empty.so initialize
$scope.phones = '';
Explanation of #LSerni seems correct.
For Linux system simply remove and reinstall your Firebug plugin. The system auto deletes all related files/folders and recreates it.
This worked for me.
The error you are having is with your JSON file. It should look like this:
[{
"name" : "Nexus S",
"snippet" : "Fast just got faster with Nexus S.",
"age" : 1
}, {
"name" : "Motorola XOOM™ with Wi-Fi",
"snippet" : "The Next, Next Generation tablet.",
"age" : 2
}, {
"name" : "MOTOROLA XOOM™",
"snippet" : "The Next, Next Generation tablet.",
"age" : 3
}]
Remember the square brackets.
Use .then rather than .success. This is an improved version of .success handling all the callbacks and calls more efficiently. It brings back the entire promise and you resolve it by referencing the .data part i.e. response.data
$http.get('app/js/phones.json').then(function(response) {
$scope.phones = response.data;
});
DEMO - Using .success
DEMO - Using .then promise
You are using the number so please use number or parse value to number example below.
<code>
var myApp = angular.module('MyApp',[]);
myApp.controller("myController",function($scope){
$scope.width=50;
$scope.height=50;
});
</code>
for me the problem was that I had forgotten to define in the controller the library
app.controller("MyCtrl", function($scope, $http) { //<- here $timeout was missing
$http.get(someUrl)
.then(function(myResponse) {
$scope.myData = myResponse.data;
$timeout(function() { //<- here $timeout was called without being defined
enableWatchers = true;
});
});
});
It works after I have changed the first line of my code to:
app.controller("MyCtrl", function($scope, $http, $timeout) { //<- here I put the $timeout
I am trying to make an app the generates 'live' graphs of Twitter word counts, basically trying to extend and exercise in Chapter 14 of NodeJS in 24 Hours. I decided to use 'Rickshaw' and I thought I'd start with simply getting a simple example working. However, while I can get a simple html page to load, I can't get a graph to display. Firefox debug indicates: "ReferenceError: Rickshaw is not defined [Break On This Error] graph = new Rickshaw.Graph( { " . That means that there is a referencing error but after a couple of hours of googling and reading, I'm not seeing it. The directory structure is correct; npm installed all modules correctly, no errors. Can anyone see what I'm missing?
Note: I am new to JS/Node and while the book is working in Express 2.x, I have been working in Express 3.x, so not sure if I've got the translation correct in all cases. The code is as follows:
package.json
{
"name":"socket.io-twitter-example",
"version": "0.0.1",
"private": "true",
"dependencies": {
"express": ">=2.5.4",
"rickshaw": ">=1.1.0"
}
}
app.js
var express = require('express'),
rickshaw = require('rickshaw'),
app = express(),
http = require('http'),
server = http.createServer(app)
server.listen(3000);
app.get('/', function (req,res) {
res.sendfile(__dirname + '/index.html');
});
index.html
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="UTF-8" />
<title>Socket.IO Twitter Example</title>
</head>
<body>
<h1>Rickshaw Example</h1>
<div id="chart"></div>
<ul class="tweets"></ul>
<script type="text/javascript" src="node_modules/rickshaw/vendor/d3.v2.js"></script> //don't think "node_modules/" is required, but doesn't work without either
<script type="text/javascript" src="node_modules/rickshaw/rickshaw.min.js"></script>
<script>
graph = new Rickshaw.Graph( {
element: document.querySelector("#chart"),
width: 285,
height: 180,
series: [{
color: 'steelblue',
data: [
{ x: 0, y: 40 },
{ x: 1, y: 49 },
{ x: 2, y: 38 },
{ x: 3, y: 30 },
{ x: 4, y: 32 } ]
}]
});
graph.render();
</script>
</body>
</html>
You need to configure express.static middleware so that express knows where to look for static resources like js and css files:
app.use(express.static( __dirname + '/public'));
Its common to put such resources into a public folder (as shown in the example above) or static folder.
If you create a public folder and organize it like
app.js
public
rickshaw
vendor
d3.v2.js
rickshaw.min.js
then you'll be able to have the files correctly loaded in your html using
<script type="text/javascript" src="/rickshaw/vendor/d3.v2.js"></script>
<script type="text/javascript" src="/rickshaw/rickshaw.min.js"></script>
See this section of the express docs for more info on and examples of middleware.
I'm trying to make a trivial postMessage example work...
in IE10
between windows/tabs (vs. iframes)
across origins
Remove any one of these conditions, and things work fine :-)
But as far as I can tell, between-window postMessage only appears to work in IE10 when both windows share an origin. (Well, in fact -- and weirdly -- the behavior is slightly more permissive than that: two different origins that share a host seem to work, too).
Is this a documented bug? Any workarounds or other advice?
(Note: This question touches on the issues, but its answer is about IE8 and IE9 -- not 10)
More details + example...
launcher page demo
<!DOCTYPE html>
<html>
<script>
window.addEventListener("message", function(e){
console.log("Received message: ", e);
}, false);
</script>
<button onclick="window.open('http://jsbin.com/ameguj/1');">
Open new window
</button>
</html>
launched page demo
<!DOCTYPE html>
<html>
<script>
window.opener.postMessage("Ahoy!", "*");
</script>
</html>
This works at: http://jsbin.com/ahuzir/1 -- because both pages are hosted at the same origin (jsbin.com). But move the second page anywhere else, and it fails in IE10.
I was mistaken when I originally posted this answer: it doesn't actually work in IE10. Apparently people have found this useful for other reasons so I'm leaving it up for posterity. Original answer below:
Worth noting: the link in that answer you linked to states that postMessage isn't cross origin for separate windows in IE8 and IE9 -- however, it was also written in 2009, before IE10 came around. So I wouldn't take that as an indication that it's fixed in IE10.
As for postMessage itself, http://caniuse.com/#feat=x-doc-messaging notably indicates that it's still broken in IE10, which seems to match up with your demo. The caniuse page links to this article, which contains a very relevant quote:
Internet Explorer 8+ partially supports cross-document messaging: it
currently works with iframes, but not new windows. Internet Explorer
10, however, will support MessageChannel. Firefox currently supports
cross-document messaging, but not MessageChannel.
So your best bet is probably to have a MessageChannel based codepath, and fallback to postMessage if that doesn't exist. It won't get you IE8/IE9 support, but at least it'll work with IE10.
Docs on MessageChannel: http://msdn.microsoft.com/en-us/library/windows/apps/hh441303.aspx
Create a proxy page on the same host as launcher. Proxy page has an iframe with source set to remote page. Cross-origin postMessage will now work in IE10 like so:
Remote page uses window.parent.postMessage to pass data to proxy page. As this uses iframes, it's supported by IE10
Proxy page uses window.opener.postMessage to pass data back to launcher page. As this is on same domain - there are no cross-origin issues. It can also directly call global methods on the launcher page if you don't want to use postMessage - eg. window.opener.someMethod(data)
Sample (all URLs are fictitous)
Launcher page at http://example.com/launcher.htm
<!DOCTYPE html>
<html>
<head>
<title>Test launcher page</title>
<link rel="stylesheet" href="/css/style.css" />
</head>
<body>
<script>
function log(msg) {
if (!msg) return;
var logger = document.getElementById('logger');
logger.value += msg + '\r\n';
}
function toJson(obj) {
return JSON.stringify(obj, null, 2);
}
function openProxy() {
var url = 'proxy.htm';
window.open(url, 'wdwProxy', 'location=no');
log('Open proxy: ' + url);
}
window.addEventListener('message', function(e) {
log('Received message: ' + toJson(e.data));
}, false);
</script>
<button onclick="openProxy();">Open remote</button> <br/>
<textarea cols="150" rows="20" id="logger"></textarea>
</body>
</html>
Proxy page at http://example.com/proxy.htm
<!DOCTYPE html>
<html>
<head>
<title>Proxy page</title>
<link rel="stylesheet" href="/css/style.css" />
</head>
<body>
<script>
function toJson(obj) {
return JSON.stringify(obj, null, 2);
}
window.addEventListener('message', function(e) {
console.log('Received message: ' + toJson(e.data));
window.opener.postMessage(e.data, '*');
window.close(self);
}, false);
</script>
<iframe src="http://example.net/remote.htm" frameborder="0" height="300" width="500" marginheight="0" marginwidth="0" scrolling="auto"></iframe>
</body>
</html>
Remote page at http://example.net/remote.htm
<!DOCTYPE html>
<html>
<head>
<title>Remote page</title>
<link rel="stylesheet" href="/css/style.css" />
</head>
<body>
<script>
function remoteSubmit() {
var data = {
message: document.getElementById('msg').value
};
window.parent.postMessage(data, '*');
}
</script>
<h2>Remote page</h2>
<input type="text" id="msg" placeholder="Type a message" /><button onclick="remoteSubmit();">Close</button>
</body>
</html>
== WORKING SOLUTION IN 2020 without iframe ==
Building on answer by tangle, I had success in IE11 [and emulated IE10 mode] using following snippet:
var submitWindow = window.open("/", "processingWindow");
submitWindow.location.href = 'about:blank';
submitWindow.location.href = 'remotePage to communicate with';
Then I was able to communicate using typical postMessage stack, I'm using one global static messenger in my scenario (although I don't suppose it's of any significance, I'm also attaching my messenger class)
var messagingProvider = {
_initialized: false,
_currentHandler: null,
_init: function () {
var self = this;
this._initialized = true;
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent, function (e) {
var callback = self._currentHandler;
if (callback != null) {
var key = e.message ? "message" : "data";
var data = e[key];
callback(data);
}
}, false);
},
post: function (target, message) {
target.postMessage(message, '*');
},
setListener: function (callback) {
if (!this._initialized) {
this._init();
}
this._currentHandler = callback;
}
}
No matter how hard I tried, I wasn't able to make things work on IE9 and IE8
My config where it's working:
IE version: 11.0.10240.16590, Update versions: 11.0.25 (KB3100773)
Building upon the answers by LyphTEC and Akrikos, another work-around is to create an <iframe> within a blank popup window, which avoids the need for a separate proxy page, since the blank popup has the same origin as its opener.
Launcher page at http://example.com/launcher.htm
<html>
<head>
<title>postMessage launcher</title>
<script>
function openWnd() {
var w = window.open("", "theWnd", "resizeable,status,width=400,height=300"),
i = w.document.createElement("iframe");
i.src = "http://example.net/remote.htm";
w.document.body.appendChild(i);
w.addEventListener("message", function (e) {
console.log("message from " + e.origin + ": " + e.data);
// Send a message back to the source
e.source.postMessage("reply", e.origin);
});
}
</script>
</head>
<body>
<h2>postMessage launcher</h2>
<p>click me</p>
</body>
</html>
Remote page at http://example.net/remote.htm
<html>
<head>
<title>postMessage remote</title>
<script>
window.addEventListener("message", function (e) {
alert("message from " + e.origin + ": " + e.data);
});
// Send a message to the parent window every 5 seconds
setInterval(function () {
window.parent.postMessage("hello", "*");
}, 5000);
</script>
</head>
<body>
<h2>postMessage remote</h2>
</body>
</html>
I'm not sure how fragile this is, but it is working in IE 11 and Firefox 40.0.3.
Right now, (2014-09-02), Your best bet is to use a proxy frame as noted in the msdn blog post that details a workaround for this issue: https://blogs.msdn.microsoft.com/ieinternals/2009/09/15/html5-implementation-issues-in-ie8-and-later/
Here's the working example: http://www.debugtheweb.com/test/xdm/origin/
You need to set up a proxy frame on your page that has the same origin as the popup. Send information from the popup to the proxy frame using window.opener.frames[0]. Then use postMessage from the proxy frame to the main page.
This solution involves adding the site to Internet Explore's Trusted Sites and not in the Local Intranet sites. I tested this solution in Windows 10/IE 11.0.10240.16384, Windows 10/Microsoft Edge 20.10240.16384.0 and Windows 7 SP1/IE 10.0.9200.17148. The page must not be included in the Intranet Zone.
So open Internet Explorer configuration (Tools > Internet Options > Security > Trusted Sites > Sites), and add the page, here I use * to match all the subdomains. Make sure the page isn't listed in the Local intranet sites (Tools > Internet Options > Security > Local Intranet > Sites > Advanced). Restart your browser and test again.
In Windows 10/Microsoft Edge you will find this configuration in Control Panel > Internet Options.
UPDATE
If this doesn't work you could try resetting all your settings in Tools > Internet Options > Advanced Settings > Reset Internet Explorer settings and then Reset: use it with caution! Then you will need to reboot your system. After that add the sites to the Trusted sites.
See in what zone your page is in File > Properties or using right click.
UPDATE
I am in a corporate intranet and sometimes it works and sometimes it doesn't (automatic configuration? I even started to blame the corporate proxy). In the end I used this solution https://stackoverflow.com/a/36630058/2692914.
This Q is old but this is what easyXDM is for, maybe check it out as a potential fallback when you detect a browser that does not support html5 .postMessage :
https://easyxdm.net/
It uses VBObject wrapper and all types of stuff you'd never want to have to deal with to send cross domain messages between windows or frames where window.postMessage fails for various IE versions (and edge maybe, still not sure 100% on the support Edge has but it seems to also need a workaround for .postMessage)
MessageChannel doesn't work for IE 9-11 between windows/tabs since it relies on postMessage, which is still broken in this scenario. The "best" workaround is to call a function through window.opener (ie. window.opener.somefunction("somedata") ).
Workaround in more detail here