I am using the geoip2 API to detect countries in my script.
I have written a script for success and error, however the error part never fires.
geoip2.country(onSuccess, onError);
I checked and saw that uBlock origin on my Firefox is blocking the geoip2 script. The error in my browser console is
ReferenceError: geoip2 is not defined
How do I handle this in jQuery and display a user to the message if I get the above error?
I am calling these scripts from index.html in the following way
<script type="text/javascript" src="//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js"></script>
<script src="/scripts/js/jqgp.js"></script>
In jqgp.js I also tried this,
if (geoip2 == undefined) {
console.log("Please disable adblock.");
}
or
if(!geoip2)
{
console.log("Please disable adblock.");
}
But it didn't execute. I am using Firefox. By the way, everything works OK if uBlock is switched off.
This should do the trick.
if (!geoip2){
alert("Please disable adblock.");
}
Related
I noticed that GitHub and Facebook are both implementing this policy now, which restricts third party scripts from being run within their experience/site.
Is there a way to detect whether a document is running against CSP using JavaScript?
I'm writing a bookmarklet, and want to give the user a message if they're on a site that doesn't support embedding a script tag.
You can try to catch a CSP violation error using an event "securitypolicyviolation"
From: https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicyViolationEvent
example:
document.addEventListener("securitypolicyviolation", (e) => {
console.log(e.blockedURI);
console.log(e.violatedDirective);
console.log(e.originalPolicy);
});
What about this. For slow connections, the timeout should probably be raised. Onload is what I used to detect it and it seems to work. If it loads then CSP obviously isn't enabled or it is configured improperly.
var CSP = 0;
frame = document.createElement('script');
frame.setAttribute('id', 'theiframe');
frame.setAttribute('src', location.protocol+'//example.com/');
frame.setAttribute('onload', 'CSP=1;');
document.body.appendChild(frame);
setTimeout(function(){if (0 == CSP){alert("CSP IS ENABLED");}}, 250);
From https://github.com/angular/angular.js/blob/cf16b241e1c61c22a820ed8211bc2332ede88e62/src/Angular.js#L1150-L1158, function noUnsafeEval
function noUnsafeEval() {
try {
/* jshint -W031, -W054 */
new Function('');
/* jshint +W031, +W054 */
return false;
} catch (e) {
return true;
}
}
Currently, there is no way to do so in shipping browsers.
However, something such as the following should work, per spec, and does in Chrome with experimental web platform features enabled in chrome://flags/:
function detectCSPInUse() {
return "securityPolicy" in document ? document.securityPolicy.isActive : false;
}
The SecurityPolicy interface (what you get from document.securityPolicy if it is implemented) has a few attributes that give more detail as to what is currently allowed.
An easy way to detect support for CSP is just by checking if JavaScript's eval()-method can be run without throwing an error, like so:
try {
eval("return false;");
} catch (e) {
return true;
}
However, this only works if CSP is actually turned on (obviously), with Content-Security-Policy being set in the response headers the page loaded with, and without 'unsafe-eval' in script-src.
I came here looking for a way to detect CSP support in browsers without CSP actually being turned on. It would seem this is not possible though.
On a side note, IE does not support CSP, only the sandbox directive in IE 10+, which, by looking at the CSP standard, does not make it a conformant web browser.
From https://hackernoon.com/im-harvesting-credit-card-numbers-and-passwords-from-your-site-here-s-how-9a8cb347c5b5:
fetch(document.location.href)
.then(resp => {
const csp = resp.headers.get('Content-Security-Policy');
// does this exist? Is is any good?
});
This will fail however with connect-src='none' and be reported.
I am checking onError event in my bookmarklet code and prompt a user to install my extension if script is not loaded.
javascript:(function(){
var s=document.createElement('script');
s.setAttribute('type','text/javascript');
s.setAttribute('src','https://example.ru/bookmarklet?hostname=%27+encodeURIComponent(location.hostname));
s.setAttribute('onerror', 'if(confirm(`Downloading from the site is possible only through the "MyExtensionName" extension. Install extension?`)){window.open("https://chrome.google.com/webstore/detail/myextensionlink");}');
document.body.appendChild(s);})();
I have html page which causes js error and an global handler for it.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<script type="text/javascript" src="js/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(function () {
window.onerror = function (errorMsg, url, lineNumber) {
alert('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber);
}
throw new Error("this is error");
});
</script>
</head>
<body>
<div>Test page</div>
</body>
</html>
I receive alert: "Error: Script error. Script: Line: 0". As you can see error info is missing. How can I get this info here like I can see errors in developer tools. Any extensions for chrome are not suitable. I must catch errors with their info in javascript.
When a syntax(?) error occurs in a script, loaded from a different origin, the details of the syntax error are not reported to prevent leaking information (see bug 363897). Instead the error reported is simply "Script error." This behavior can be overriden in some browsers using the crossorigin attribute on and having the server send the appropriate CORS HTTP response headers. A workaround is to isolate "Script error." and handle it knowing that the error detail is only viewable in the browser console and not accessible via JavaScript.
I also ran into this. See notes section here: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror
This implies the development setup might need some adjustment to avoid this policy issue. I'm merely guessing here, so don't take it for granted.
I am just adding answer for the sake of those who came here looking.
Source: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror
Please go this URL, as you can see there are five parameters to
window.onerror = function(message, source, lineno, colno, error) { ... }
the last one is the one you need, it has complete record of what you see in console in case of error.
message: error message (string). Available as event (sic!) in HTML onerror="" handler.
source: URL of the script where the error was raised (string)
lineno: Line number where error was raised (number)
colno: Column number for the line where the error occurred (number)
error: Error Object (object)
Then Error Object has two properties
message
stack
stack is the one which will contain all the information you required.
use console.log(errorMsg, url, lineNumber)instead of alert to get more readable log. You can see the log in browser developer console. Also you can check the use of try..catch for better error handling.
use jquery script with anonymous attirbute, and the script server response header with [access-control-allow-origin:*]. Your error throw code is runned with jquery callback.
errorMsg is NOT the message "this is error"; it is Script error., which is precisely what you're seeing. You simply don't get the error message that way. onerror is unsuited to replace a try-catch block.
we are using Highcharts and get the following errors on an intermittent basis. There appears to be no reason we can see why this happens in Chrome:
Uncaught Highcharts error #16: www.highcharts.com/errors/16
VM210:16 HighCharts was already loaded
VM210:25 Uncaught TypeError: $(...).highcharts is not a function
Highcharts is loaded in a base.html file that is included in Django with the following includes:
<script src="//code.highcharts.com/highcharts.js"></script>
<script src="//code.highcharts.com/modules/exporting.js"></script>
<script src="//code.highcharts.com/modules/offline-exporting.js"></script>
We've been struggling with this issue and have now added the following code to a html page that is ajax loaded:
if (window.Highcharts === undefined) {
console.log("Highcharts is not loaded, fetching...");
$.getScript("http://code.highcharts.com/highcharts.js", function () {
alert("HighCharts was loaded");
});
}
else {
console.log("HighCharts was already loaded");
}
Seems to make no difference.
So I think the problem relates to the fact that the page is loaded from ajax. I've put in the above code following a read through of stackoverflow.
Thanks.
Paul
In my case these "vm210" errors came from a pop-up blocker I had installed in Chrome.
I noticed that GitHub and Facebook are both implementing this policy now, which restricts third party scripts from being run within their experience/site.
Is there a way to detect whether a document is running against CSP using JavaScript?
I'm writing a bookmarklet, and want to give the user a message if they're on a site that doesn't support embedding a script tag.
You can try to catch a CSP violation error using an event "securitypolicyviolation"
From: https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicyViolationEvent
example:
document.addEventListener("securitypolicyviolation", (e) => {
console.log(e.blockedURI);
console.log(e.violatedDirective);
console.log(e.originalPolicy);
});
From https://github.com/angular/angular.js/blob/cf16b241e1c61c22a820ed8211bc2332ede88e62/src/Angular.js#L1150-L1158, function noUnsafeEval
function noUnsafeEval() {
try {
/* jshint -W031, -W054 */
new Function('');
/* jshint +W031, +W054 */
return false;
} catch (e) {
return true;
}
}
What about this. For slow connections, the timeout should probably be raised. Onload is what I used to detect it and it seems to work. If it loads then CSP obviously isn't enabled or it is configured improperly.
var CSP = 0;
frame = document.createElement('script');
frame.setAttribute('id', 'theiframe');
frame.setAttribute('src', location.protocol+'//example.com/');
frame.setAttribute('onload', 'CSP=1;');
document.body.appendChild(frame);
setTimeout(function(){if (0 == CSP){alert("CSP IS ENABLED");}}, 250);
Currently, there is no way to do so in shipping browsers.
However, something such as the following should work, per spec, and does in Chrome with experimental web platform features enabled in chrome://flags/:
function detectCSPInUse() {
return "securityPolicy" in document ? document.securityPolicy.isActive : false;
}
The SecurityPolicy interface (what you get from document.securityPolicy if it is implemented) has a few attributes that give more detail as to what is currently allowed.
An easy way to detect support for CSP is just by checking if JavaScript's eval()-method can be run without throwing an error, like so:
try {
eval("return false;");
} catch (e) {
return true;
}
However, this only works if CSP is actually turned on (obviously), with Content-Security-Policy being set in the response headers the page loaded with, and without 'unsafe-eval' in script-src.
I came here looking for a way to detect CSP support in browsers without CSP actually being turned on. It would seem this is not possible though.
On a side note, IE does not support CSP, only the sandbox directive in IE 10+, which, by looking at the CSP standard, does not make it a conformant web browser.
From https://hackernoon.com/im-harvesting-credit-card-numbers-and-passwords-from-your-site-here-s-how-9a8cb347c5b5:
fetch(document.location.href)
.then(resp => {
const csp = resp.headers.get('Content-Security-Policy');
// does this exist? Is is any good?
});
This will fail however with connect-src='none' and be reported.
I am checking onError event in my bookmarklet code and prompt a user to install my extension if script is not loaded.
javascript:(function(){
var s=document.createElement('script');
s.setAttribute('type','text/javascript');
s.setAttribute('src','https://example.ru/bookmarklet?hostname=%27+encodeURIComponent(location.hostname));
s.setAttribute('onerror', 'if(confirm(`Downloading from the site is possible only through the "MyExtensionName" extension. Install extension?`)){window.open("https://chrome.google.com/webstore/detail/myextensionlink");}');
document.body.appendChild(s);})();
function getViews(){
$.get (
"http://www.roblox.com/User.aspx?ID=16",
function parse(data) {
var userviews = $(data).find("#ctl00_cphRoblox_rbxUserStatisticsPane_lProfileViewsStatistics").html();
alert(userviews);
}
);
}
getViews();
I basically want it to do the same thing as the line below, except there's more to my jquery function that I didnt give because I know that works:
alert(document.getElementById('ctl00_cphRoblox_rbxUserStatisticsPane_lProfileViewsStatistics').innerHTML)
You don't give details but I suspect your success callback is not even executing (i.e., the alert() is not firing) because the AJAX request is failing. Your code will possibly not work unless it's hosted at http://www.roblox.com.
I can see the following error in the browser console:
XMLHttpRequest cannot load http://www.roblox.com/User.aspx?ID=16.
Origin http://test.local is not allowed by Access-Control-Allow-Origin.
In Firebug, Chrome and recent IE you can open the console with F12. In Firefox you can use Ctrl+Shift+K.