Why can't load js file in my local apache2 server? - javascript

In my local domain's webpage , both
jq.src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js";
jq.src = http://127.0.0.1/js/jquery-3.3.1.min.js
can be loaded.
In the stackoverflow's webpage,right click to enter into chrome's inspect--console.
const jq = document.createElement('script');
jq.src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js";
document.head.appendChild(jq);
jq.addEventListener('load', () => {
console.log("hello world");
console.log($ === jQuery);
});
The remote jquery.js file can be loaded,now to replace it with local js file--http://127.0.0.1/js/jquery-3.3.1.min.js .
Why can't load the js file in my local apache2?

Sites you are visiting can apply security policy for javascript - which includes the debugger. I think what you are seeing is the application of the content security policy associated with the web page you are visiting.
You can see this in the page headers. In Chrome (as explained here), you can view the html headers sent with the page:
Open the developer panel, select the "network" tab, and reload the page.
For stackoverflow, look under the "name" column for "stackoverflow.com" - there may be two if you originally loaded it via http, so find the one which is https - probably the second one. Click that one, and select the "headers" tab on the right. You will see in amongst the response headers:
content-security-policy: upgrade-insecure-requests
This is explained here.
Basically, it tells the browser that all http requests should be "upgraded" to https. So when you try to access http://127.0.0.1/..., your browser upgrades the request to https://127.0.0.1/..., which your local server probably isn't set up to handle.
This is not limited to Chrome - all modern browsers should do this.
I browsed, for example, a few sites with Safari, and, in some cases, got an error message, such as on GitHub:
Refused to load https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js because
it does not appear in the script-src directive of the Content Security Policy.
That is another variety of content security policies you can read about here.

try
jq.setAttribute('src',"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js");
jq.setAttribute('crossOrigin',"Anonymos")
jq.onload=onFinish;

Related

How to overcome Ajax Content Security Policy directive?

I am injecting some JS code on various websites (using Selenium and Python) to send POST requests to my local web server. On some websites it works fine. But mostly, I don't get the requests. Figured it's because of the Content Security Policy.
For example, when I try to run the code using Console in Chrome on github.com, I get a following error:
Refused to connect to 'http://10.50.50.127:7777/' because it violates
the following Content Security Policy directive: "connect-src 'self'
uploads.github.com status.github.com collector.githubapp.com
api.github.com www.google-analytics.com ...".
My code looks like this:
function sendData() {
var request = new XMLHttpRequest();
request.open('POST', 'http://10.50.50.127:7777', false);
request.send("test");
}
I did some research on my own, and found a possible solution - to use a local proxy server and send data to a relative path like "/test". But it's pretty complicated to write a proxy server from scratch.
So, what can I do to overcome this Content Security Policy?
If your using Chrome and you want to disable Content Security Policy you can also use a plugin called Disable Content-Security-Policy from Chrome Web Store. This is the plugin for Chrome to disable headers.
I inject JS via Tampermonkey (Chrome) and this works fine.
If you controlled over both of sides then you can use.
https://easyxdm.net/wp/
Regards
I figured it! Turns out you can just disable all of the security checks:
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--disable-web-security')
chrome_options.add_argument('--allow-running-insecure-content')
browser = webdriver.Chrome(chrome_options=chrome_options)

External file fail to load on 'load' function

I want to load content of external text file (demo.txt) in my div on button click.
Text file containes text 'Demo text.'
But it shows error
XMLHttpRequest cannot load file:///C:/Users/Tom/Desktop/jQuery%20thenewboston/76.)%20Load%20function/demo.txt. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
on my browser console.
$(document).ready(function(){
$('#button_file').on('click',function(){
$('#load_html').load('demo.txt');
});
});
<button type="button" id="button_file">Load file</button>
<br />
<div id="load_html" >
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am a beginner in jquery , please comment below for any query.
You cannot get the result because the remote site doesn't have CORS enabled: If you look at the console, you'll see:
(Reason: CORS header 'Access-Control-Allow-Origin' missing).
You can bypass CORS by using something like anyorigin.com, i.e.:
$.getJSON('http://anyorigin.com/get/?url=http%3A//thenewboston....&callback=?', function(data){
$('#div-data').html(data.contents);
});
PS: If it's a local file, make sure you load it on the same address as the script, (localhost, 127.0.0.1, 192.168.1.1, etc...)
You are being restricted by HTTP access control (CORS). The file you are requesting asynchronously needs to be from the same domain or the domain you are accessing it from needs to allow your domain to access it. As you are using the file:/// protocol you need to allow it, so check out this if that's the way you wish to go.
Alternatively you can create a local web server to host your site an allow access to the file on the same domain.
In order to make this work you need to use a web server instead of using just clicking on the html file.
Check XAMPP
Unfortunately, Google Chrome doesn't allow cross-origin request although Firefox does.
Alternatively, if the text file is short you can store it in an object and place it wherever you like.
text_file = {
contents = 'content';
}
$('.button_class').on('click',function(){
$('.div').html(text_file.contents);
});
I would never suggest you use this but if it's a small project, a one page application that nobody will see the code to - desperate times call for desperate measures.
The best thing to do is to use XAMPP and PHP.
Load in from your database the content you would like to show.
You can read the PHP documentation or watch online tutorials , I personally suggest TheNewBoston PHP Tutorials with Alex Garrett

How to avoid Uncaught SecurityError: Blocked a frame with origin with phonegap

I am trying to build a phonegap app, which acts as a mini browser for a clients website. The clients customers would open this app, it would have a list of favorites. They could click on one of these favorites and it'd open that favorite within the minibrowser.html page. The minibrowser.html, has a favorites button at the top, then it has an iframe that should act as the browser. I open the favorites by changing the iframes src. I can capture the title/url with this code
$iframe.on('load', () => {
try {
console.log($iframe[0].contentDocument.title);
currentUrl = $iframe[0].contentDocument.URL;
console.log(currentUrl);
} catch (e) {}
});
But the problem occurs when the webpage within the iframe trys to access window.top with this line
window.top.scrollTo(0,1);
That throws the error:
Uncaught SecurityError: Blocked a frame with origin "https://webapp.company.com" from accessing a frame with origin "file://". The frame requesting access has a protocol of "https", the frame being accessed has a protocol of "file". Protocols must match.
Is there anyway to spoof window.top for the iframe? Is there anyway of doing this without hosting the phonegap code on webapp.company.com. I do not have access to webapp.company.com
Due to the nature of the HTTPS protocol, it's mandatory for the server to specify if it's accepting third-party frame distribution (something like what you're trying to do). This is done as it's a major flaw when it comes to security.
Imagine, a person may use a simple variant of this hack to show a part of the Facebook page, and capture your account details. This policy prevents that.
A simple workaround would be to use some sort of URL shortener, or a proxy forwarder.
For a quick example: http://codepen.io/nakshatra334/pen/OMgLLP and open up the console; you'll see the content security policy.
The header, X-Frame-Options is denying this as people may use this for illicit purposes.

Jquery load https url

I have this problem. In external web site I have a script like this:
<div id="idtest"></div>
<script src="//example.com/widget.js" type="text/javascript"></script>
example.com is in https (allow both http and https). In the server in the script widget.js I have:
$('#idtest').load("https://example.com/index.html")
I get this error: Mixed Content: The page at 'thepage' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://example.com/index.html'. This request has been blocked; the content must be served over HTTPS.
I don't understand: why the error and why the endpoint is in "http"?
thanks
EDIT
More information:
if in the widget.js I do this:
$('#idtest').load("./index.html")
the content is load and all works perfectly if I load the script in my site.
If I do something like:
x = "https://example.com"
$('#idtest').load(x + "/index.html")
or
$('#idtest').load("https://example.com/index.html")
I get the error (if I put the script in my site or in external site). Why?
EDIT 2
more informations:
my site is in django
EDIT 3
In firefox I load the page in https and http. It doesn't work in Chrome. I see this situation in firefox net analyzer when call the url :
302 https://example.com/index.html
200 http://example.com/index.html [mixed content]
What understand this situation (https to http)? Could be a Django redirect problem?
A mixed content error happens when:
you try to load secure content SSL(https) on a page served insecurely (http) served
Or the opposite
you try to load insecure content (http) on a page served securely SSL(https) served
Your error message is warning that your calling page has been loaded in insecure mode
You haven't explicitly explained this, but your error indicated your page is being served without SSL. When you try to load a protected resource this becomes a mixed mode problem of protected resources and insecure.
If possible, you try to serve the reference file the same way
You can serve your main page in SSL (https)
You can request the partial page in http
$('#idtest').load("http://example.com/index.html")
or
Just as you have resolved it, request the partial page without protocol. Now your loaded file will be loaded using the protocol used by your page.
About your specific resource:
I tried loading:
http://example.com/index.html
and
https://example.com/index.html
The result was the same. I got a simple page with the message:
Example Domain
This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission.
More information...
I think it is more a problem of cross origin domain.
the $.load function of jquery use ajax to load the url and so you cannot do cross domain call if the target URL does not implement CORS headers.
In your example, the server example.com must return a header
Access-Control-Allow-Origin: *
You can also replace * with the domain of the page that want to load the content by AJAX.
A good blog post on how to use CORS:
http://www.html5rocks.com/en/tutorials/cors/
I had this issue on Ruby on Rails webpage and the the mistake was to use "_url" helper instead of "_path" helper, on a https webpage:
in a view:
wrong: borrar_linea_factura_url(l)
ok: borrar_linea_factura_path(l)
As a recap of said before:
"_url" helper generates /controller/action/params
"_path" helper generates https://controller/action/params

... this content should also be loaded over HTTPS

Good day.
Site https://mult-privet.com/
In my Chrome console, I see this error:
[blocked] The page at 'https://yandex.st/share/ya-share-cnt.html?url=
https%3A%2F%2Fmult-privet.com%2F&services=yaru,
vkontakte,facebook,twitter,odnoklassniki,moimir'
was loaded over HTTPS, but ran insecure content
from 'http://connect.odnoklassniki.ru/dk?st.cmd=extOneClickLike&uid=odklocs0&
ref=https%3A%2F%2Fmult-privet.com%2F':
this content should also be loaded over HTTPS.
Why should this URI also be loaded over HTTPS ?
Why am I getting this error, and how do I remove it?
On the right side of the Chrome address bar, click on the shield icon, then click "Load unsafe script". Done!
Why this content should also be loaded over HTTPS ?
Because:
if you have unsecured content being injected into an otherwise secure page, the unsecured content can be intercepted, replaced and thus render the secure content insecure
the browser can't honestly continue to tell the user that the page is secure when parts of it are not
Tell me please why i get this error
You are loading HTTP without SSL content into an HTTP with SSL page.
and how remove this?
Use HTTPS for everything on the page.
Why you are getting this error
Quentin's answer explains this pretty well. I would clarify that you are getting a mixed content error.
How to fix this error
Although Quentin's answer offers the most ideal fix, it is sometimes more convenient to solve mixed content errors using a protocol-relative URL, where the http[s]?: prefix is removed from the URL. For example, change this:
http://connect.odnoklassniki.ru/dk?st.cmd=extOneClickLike&uid=odklocs0&
ref=https%3A%2F%2Fmult-privet.com%2F
to this:
//connect.odnoklassniki.ru/dk?st.cmd=extOneClickLike&uid=odklocs0&
ref=https%3A%2F%2Fmult-privet.com%2F
by removing the http: prefix. It will let the browser determine the protocol. When using the protocol relative URL in the above example, if you are on an SSL encrypted page the browser will access the https://connect.odnoklassniki... URL, and on a non-SSL page, it will access the http://connect.odnoklassniki... URL, assuming that both protocols work for the URL.
There are, however, some pitfalls in using protocol-relative URLs, like ensuring that the server behind the URL is capable of serving both http and https protocols. This SO post addresses more reasons to use protocol-relative URLs.

Categories