When I try to change the linked reference of a local JavaScript file to a GitHub raw version my test file stops working. The error is:
Refused to execute script from ... because its MIME type (text/plain) is not executable, and strict MIME type checking is enabled.
Is there a way to disable this behavior or is there a service that allows linking to GitHub raw files?
Working code:
<script src="bootstrap-wysiwyg.js"></script>
Non-working code:
<script src="https://raw.github.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js"></script>
There is a good workaround for this, now, by using jsdelivr.net.
Steps:
Find your link on GitHub, and click to the "Raw" version.
Copy the URL.
Change raw.githubusercontent.com to cdn.jsdelivr.net
Insert /gh/ before your username.
Remove the branch name.
(Optional) Insert the version you want to link to, as #version (if you do not do this, you will get the latest - which may cause long-term caching)
Examples:
http://raw.githubusercontent.com/<username>/<repo>/<branch>/path/to/file.js
Use this URL to get the latest version:
http://cdn.jsdelivr.net/gh/<username>/<repo>/path/to/file.js
Use this URL to get a specific version or commit hash:
http://cdn.jsdelivr.net/gh/<username>/<repo>#<version or hash>/path/to/file.js
For production environments, consider targeting a specific tag or commit-hash rather than the branch. Using the latest link may result in long-term caching of the file, causing your link to not be updated as you push new versions. Linking to a file by commit-hash or tag makes the link unique to version.
Why is this needed?
In 2013, GitHub started using X-Content-Type-Options: nosniff, which instructs more modern browsers to enforce strict MIME type checking. It then returns the raw files in a MIME type returned by the server, preventing the browser from using the file as-intended (if the browser honors the setting).
For background on this topic, please refer to this discussion thread.
This is no longer possible. GitHub has explicitly disabled JavaScript
hotlinking, and newer versions of browsers respect that setting.
Heads up: nosniff header support coming to Chrome and Firefox
rawgithub.com redirects to rawgit.com So the above example would now be
http://rawgit.com/user/package/master/link.min.js
GitHub Pages is GitHub’s official solution to this problem.
raw.githubusercontent makes all files use the text/plain MIME type, even if the file is a CSS or JavaScript file. So going to https://raw.githubusercontent.com/‹user›/‹repo›/‹branch›/‹filepath› will not be the correct MIME type but instead a plaintext file, and linking it via <link href="..."/> or <script src="..."></script> won’t work—the CSS won’t apply / the JS won’t run.
GitHub Pages hosts your repo at a special URL, so all you have to do is check-in your files and push. Note that in most cases, GitHub Pages requires you to commit to a special branch, gh-pages.
On your new site, which is usually https://‹user›.github.io/‹repo›, every file committed to the gh-pages branch (the most recent commit) is present at this url. So then you can link to your js file via <script src="https://‹user›.github.io/‹repo›/file.js"></script>, and this will be the correct MIME type.
Do you have build files?
Personally, my recommendation is to run this branch parallel to master. On the gh-pages branch, you can edit your .gitignore file to check in all the dist/build files you need for your site (e.g. if you have any minified/compiled files), while keeping them ignored on your master branch. This is useful because you typically don’t want to track changes in build files in your regular repo. Every time you want to update your hosted files, simply merge master into gh-pages, rebuild, commit, and then push.
(protip: you can merge and rebuild in the same commit with these steps:)
$ git checkout gh-pages
$ git merge --no-ff --no-commit master # prepare the merge but don’t commit it (as if there were a merge conflict)
$ npm run build # (or whatever your build process is)
$ git add . # stage the newly built files
$ git merge --continue # commit the merge
$ git push origin gh-pages
https://raw.githack.com/
found this site supply a CDN for
remove nosniff http header
fix mime type by ext name
and this site:
https://rawgit.com/
NOTE: RawGit has reached the end of its useful life
You can also use a browser extension to remove the X-Content-Type-Options response header for raw.githubusercontent.com files. There are a couple of browser extensions to modify response headers.
Requestly: Chrome & Firefox
Modify Header Value: Firefox
Remove X-Content-Type-Options response header using Requestly
Install Requestly for your browser
Open Rules Page
Click create rule & Select Modify Headers
In Source field, enter Url -> Contains -> raw.githubusercontent.com
In Response Headers section, Remove -> X-Content-Type-Options
How to test
I created a simple JS Fiddle to test out if we can use raw github files as scripts in our code. Here is the Fiddle with the following code
<center id="msg"></center>
<script src="https://raw.githubusercontent.com/sachinjain024/practicebook/master/web-extensions-master/storage/background.js"></script>
<script>
try {
if (typeof BG.Methods !== 'undefoned') {
document.getElementById('msg').innerHTML = 'Script evaluated successfully!';
}
} catch (e) {
document.getElementById('msg').innerHTML = 'Problem evaluating script';
}
</script>
If you see Script evaluated successfully!, It means you are able to use raw github file in your code
Otherwise Problem evaluating script indicates that there is some problem while executing the script from raw github source.
Note This will only work on your machine So you won't be able to deploy to production. This approach lets you quickly use the files in any Github repostiory without much hassle.
Disclaimer: I am the author of Requestly So you can blame for anything you don't like.
My use case was to load 'bookmarklets' direclty from my Bitbucket account which has same restrictions as Github. The work around I came up with was to AJAX for the script and run eval on the response string, below snippet is based on that approach.
<script>
var sScriptURL ='<script-URL-here>';
var oReq = new XMLHttpRequest();
oReq.addEventListener("load",
function fLoad() {eval(this.responseText + '\r\n//# sourceURL=' + sScriptURL)});
oReq.open("GET", sScriptURL); oReq.send(); false;
</script>
Note that appending of sourceURL comment is to allow for debuging of the script within browser's developer tools.
To make things clear and short
//raw.githubusercontent.com --> //rawgit.com
Note that this is handled by rawgit's development hosting and not their cdn for production hosting
When a file is uploaded to github you can use it as external source or free hosting. Troy Alford has explained it well above. But to make it easier let me tell you some easy steps then you can use a github raw file in your site:
Here is your file's link:
https://raw.githubusercontent.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js
Now to execute it you have to remove https:// and the dot( . ) between raw and githubusercontent
Like this:
rawgithubusercontent.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js
Now when you will visit this link you will get a link that can be used to call your javascript:
Here is the final link:
https://rawgit.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js
Similarly if you host a css file you have to do it as mentioned above. It is the easiest way to get simple link to call your external css or javascript file hosted on github.
I hope this is helpful.
Referance URL: http://101helper.blogspot.com/2015/11/store-blogger-codes-on-github-boost-blogger-speed.html
I found the error was shown due to the comments at the beginning of file , You can solve this issue , by simply creating your own file without comment and push to git, it shows no error
For proof you can try these two file with same code of easy pagination :
without comment
with comment
I had the same issue as you, what I did is change to
<script type="application/javascript" src="bootstrap-wysiwyg.js"></script>
It works for me.
Example
original
https://raw.githubusercontent.com/antelove19/qrcodejs/master/qrcode.min.js
cdn.jsdelivr.net
https://cdn.jsdelivr.net/gh/antelove19/qrcodejs/qrcode.min.js
Most simple way:
<script type="text/plain" src="http://raw.githubusercontent.com/user/repo/branch/file.js"></script>
Served by GitHub, and very reliable.
With text/plain
Without text/plain
raw.github.com is not truely raw access to file asset,
but a view rendered by Rails.
So accessing raw.github.com is much heavier than needed.
I don't know why raw.github.com is implemented as a Rails view.
Instead of fix this route issue, GitHub added a X-Content-Type-Options: nosniff header.
Workaround:
Put the script to user.github.io/repo
Use a third party CDN like rawgit.com.
Alternatively, if generating your markup server-side, you can just fetch and inject.
For example, in JSTL you could do this:
<script type="text/javascript">
<c:import url="https://raw.github.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js" />
</script>
They don't allow hotlinking for a reason, so probably bad form if you want to be a good citizen. I'd suggest you cache that javascript and only actually re-fetch periodically as you see fit.
Related
In chrome My SSL related page got blank on other browser it works fine.
It gives the error message
"The page at https://xyz.com/test/checkout ran insecure content from http://xyz.com/test/checkout/css/styles.css"
In my website some pages are on SSL,I have only one masterpage which is used in both type of pages(http and https),I want to use my css and js which will work on both conditions.
Check any resources in the CSS file (like images and background images).
If they link to the HTTP domain see if you can rewrite them to be a relative path, so the HTTP/HTTPS switching is automatic.
It is safe (and permitted) to include CSS that is served over HTTPS in a web-page that is served over regular HTTP; so, one option is to use https://xyz.com/test/checkout/css/styles.css in all cases.
Another option, since the path seems to be the same for both versions, is to use //xyz.com/test/checkout/css/styles.css (not specifying the protocol); then the same protocol will be used for the CSS as is used for the HTML.
There are probably links in your CSS file that relate to a non-secure location.
I would suggest checking that file so you can make any updates.
Alternatively, on your server you could do a URL rewrite so anything that comes through on HTTP is re-written to HTTPS.
Using a protocol-independent absolute path is what you can leverage:
http://blog.httpwatch.com/2010/02/10/using-protocol-relative-urls-to-switch-between-http-and-https/
I'm trying to create a website that can be downloaded and run locally by launching its index file.
All the files are local, no resources are used online.
When I try to use the AJAXSLT plugin for jQuery to process an XML file with an XSL template (in sub directories), I receive the following errors:
XMLHttpRequest cannot load file:///C:/path/to/XSL%20Website/data/home.xml. Origin null is not allowed by Access-Control-Allow-Origin.
XMLHttpRequest cannot load file:///C:/path/to/XSL%20Website/assets/xsl/main.xsl. Origin null is not allowed by Access-Control-Allow-Origin.
The index file making the request is file:///C:/path/to/XSL%20Website/index.html while the JavaScript files used are stored in file:///C:/path/to/XSL%20Website/assets/js/.
How can I do to fix this issue?
For instances where running a local webserver is not an option, you can allow Chrome access to file:// files via a browser switch. After some digging, I found this discussion, which mentions a browser switch in opening post. Run your Chrome instance with:
chrome.exe --allow-file-access-from-files
This may be acceptable for development environments, but little else. You certainly don't want this on all the time. This still appears to be an open issue (as of Jan 2011).
See also: Problems with jQuery getJSON using local files in Chrome
Essentially the only way to deal with this is to have a webserver running on localhost and to serve them from there.
It is insecure for a browser to allow an ajax request to access any file on your computer, therefore most browsers seem to treat "file://" requests as having no origin for the purpose of "Same Origin Policy"
Starting a webserver can be as trivial as cding into the directory the files are in and running:
python -m http.server
[Edit Thanks #alextercete, for pointing out that it has updated in Python3]
This solution will allow you to load a local script using jQuery.getScript(). This is a global setting but you can also set the crossDomain option on a per-request basis.
$.ajaxPrefilter( "json script", function( options ) {
options.crossDomain = true;
});
What about using the javascript FileReader function to open the local file, ie:
<input type="file" name="filename" id="filename">
<script>
$("#filename").change(function (e) {
if (e.target.files != undefined) {
var reader = new FileReader();
reader.onload = function (e) {
// Get all the contents in the file
var data = e.target.result;
// other stuffss................
};
reader.readAsText(e.target.files.item(0));
}
});
</script>
Now Click Choose file button and browse to the file file:///C:/path/to/XSL%20Website/data/home.xml
Here is an applescript that will launch Chrome with the --allow-file-access-from-files switch turned on, for OSX/Chrome devs out there:
set chromePath to POSIX path of "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
set switch to " --allow-file-access-from-files"
do shell script (quoted form of chromePath) & switch & " > /dev/null 2>&1 &"
Launch chrome like so to bypass this restriction: open -a "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --args --allow-file-access-from-files.
Derived from Josh Lee's comment but I needed to specify the full path to Google Chrome so as to avoid having Google Chrome opening from my Windows partition (in Parallels).
The way I just worked around this is not to use XMLHTTPRequest at all, but include the data needed in a separate javascript file instead. (In my case I needed a binary SQLite blob to use with https://github.com/kripken/sql.js/)
I created a file called base64_data.js (and used btoa() to convert the data that I needed and insert it into a <div> so I could copy it).
var base64_data = "U1FMaXRlIGZvcm1hdCAzAAQA ...<snip lots of data> AhEHwA==";
and then included the data in the html like normal javascript:
<div id="test"></div>
<script src="base64_data.js"></script>
<script>
data = atob(base64_data);
var sqldb = new SQL.Database(data);
// Database test code from the sql.js project
var test = sqldb.exec("SELECT * FROM Genre");
document.getElementById("test").textContent = JSON.stringify(test);
</script>
I imagine it would be trivial to modify this to read JSON, maybe even XML; I'll leave that as an exercise for the reader ;)
You can try putting 'Access-Control-Allow-Origin':'*' in response.writeHead(, {[here]}).
use the 'web server for chrome app'. (you actually have it on your pc, wether you know or not. just search it in cortana!). open it and click 'choose file' choose the folder with your file in it. do not actually select your file. select your files folder then click on the link(s) under the 'choose folder' button.
if it doesnt take you to the file, then add the name of the file to the urs. like this:
https://127.0.0.1:8887/fileName.txt
link to web server for chrome: click me
If you only need to access the files locally then you can include the exact path to the file, rather than using
../images/img.jpg
use
C:/Users/username/directoryToImg/img.jpg
The reason CORS is happening is because you are trying to traverse to another directory within a webpage, by including the direct path you are not changing directory, you are pulling from a direct location.
Just had a quick question to throw out and see if there was a solution for this...
Let's pretend I have no access to the server.
I load up a webpage and find out that they have a Javascript file loading from a subfolder (let's say /scripts/js/some.js)
Now, I want to make changes to this file locally and test it against the whole site without downloading the entire site to a local folder.
Does anyone know of a way I can override the loading of that remote js file in favor of a local/edited copy of it?
Try using noscript or adblock to block the server side script from loading. Then use greasemonkey to load your own script.
I actually found a solution for this. Posting details for anyone that comes here looking for it.
Privoxy (www.privoxy.org/) [Free] Allows this for the most part through a redirect. Though Firefox may block the redirect depending on where you put it. This means you most likely will not be able to save the file locally and reference it via file://etc/
( I wish I had a way to tell you how to statically fiddle with JavaScript on web pages you have limited access to... but I have not found it. If an answer comes along I will accept it over this. )
Of course, you have to set up Privoxy, and use it as a local proxy server. It's pretty simple if you only use it temporarily: Just point your browser to proxy 127.0.0.1 on port 8118 with it running.
You have to add a redirect "default action" (Options > Edit Default Actions) to redirect the browser to use your new copy:
{ +redirect{/newLocation/some.js} }
/scripts/js/some.js
If you want a way to use a local file instead of a remote file (in any web browser), I highly recommend Charles Web Proxy. http://www.charlesproxy.com/
In Charles, go to the Tools menu and select Map Local. Add a new mapping by entering the address of the file on the web you would like loaded from your disk.
This technique will for all sorts of files (JavaScript, CSS, SWF). Of course you have the option to temporarily disable this feature, and it will only work while Charles is running. Very handy.
While your solution with proxy is somewhat more permanent, I found that with Fiddler you can do it with almost no configuration:
How to replace Javascript of production website with local Javascript?
In a browser that supports FileReader such as Chrome, yes, in combination with 'eval' to execute arbitrary JS. In your HTML add a button for the user to press:
<form>
<input type="file" name="file"
onchange="loadJS(event.target.files);">
</form>
In your scripts add:
function load() {
var reader = new FileReader();
reader.onload = function(evt) {
eval(evt.target.result);
};
reader.readAsText(files[0]);
}
I have this situation where we have media files stored on a global CDN. Our web app is hosted on it's own server and then when the media assets are needed they are called from the CDN url. Recently we had a page where the user can download file attachments, however some of the file types were opening in the browser instead of downloading (such as MP3). The only way around this was to manually specify the HTTP response to attach the file but the only way I could achieve this was to download the file from CDN to my server and then feed it back to the user, which defeats the purpose of having it on the global CDN. Instead I am wondering if there is some client side solution for this?
EDIT: Just found this somewhere, though I'm not sure if it will work right in all the browsers?
<body>
<script>
function downloadme(x){
myTempWindow = window.open(x,'','left=10000,screenX=10000');
myTempWindow.document.execCommand('SaveAs','null','download.pdf');
myTempWindow.close();
}
</script>
<a href=javascript:downloadme('/test.pdf');>Download this pdf</a>
</body>
RE-EDIT: Oh well, so much for that idea -> Does execCommand SaveAs work in Firefox?
Does your CDN allow you to specify the HTTP headers? Amazon cloudfront does, for example.
I found an easy solution to this that worked for me. Add a URL parameter to the file name. This will trick the browser into bypassing it's built in file mappings. For examaple, instead of http://mydomain.com/file.pdf , set your client side link up to point to http://mydomain.com/file.pdf? (added a question mark)
Lets assume I have a file on a CDN (Cloud Files from Rackspace) and a static html page with a link to that file. Is there any way I can force download this file (to prevent it from opening in the browser -- for mp3s for example)?
We could make our server read the file and set the corresponding header to:
header("Content-Type: application/force-download")
but we have about 5 million downloads per month so we would rather let the CDN take care of that.
Any ideas?
There’s no way to do this in HTML or JavaScript. There is now! (Ish. See #BruceAldrige’s answer below.)
The HTTP Content-Disposition header is what tells browsers to download the files, and that’s sent by the server. You have to configure the CDN to send that header with whichever files you want to browser to download instead of display.
Unhelpfully, I’m entirely unfamiliar with Rackspace’s Cloud Files service, so I don’t know if they allow this, nor how to do it. Just found a page from December 2009 that suggests not thought, sadly:
Cloud Files cannot serve a file with the 'Content-Disposition: attachment' HTTP header. Therefore, a download link that would work perfectly in any other service may result in the browser rendering the file directly. This was confirmed by Rackspace engineers. :-(
http://drupal.org/node/656714
I know that you can with Amazon’s CloudFront service, as it’s backed by S3 (see e.g. http://blog.cloudberrylab.com/2009/06/how-to-set-custom-http-headers-for.html)
You can use the download attribute:
<a href="http..." download></a>
https://stackoverflow.com/a/11024735/21460
However, it’s not currently supported by Safari (7) or IE (11).
Yes, you can do this through the cloudfiles API. Using the method stream allows you to stream the contents of files in - setting your own headers etc.
A crazy idea: download via XMLHttpRequest and serve a data: URL with the content type you want? :P