Link and execute external JavaScript file hosted on GitHub

前端 未结 15 846
感动是毒
感动是毒 2020-11-22 04:08

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 exe

相关标签:
15条回答
  • 2020-11-22 04:23

    There is a good workaround for this, now, by using jsdelivr.net.

    Steps:

    1. Find your link on GitHub, and click to the "Raw" version.
    2. Copy the URL.
    3. Change raw.githubusercontent.com to cdn.jsdelivr.net
    4. Insert /gh/ before your username.
    5. Remove the branch name.
    6. (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.

    0 讨论(0)
  • 2020-11-22 04:25

    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.

    0 讨论(0)
  • 2020-11-22 04:27

    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
    
    0 讨论(0)
  • 2020-11-22 04:28

    rawgithub.com redirects to rawgit.com So the above example would now be

    http://rawgit.com/user/package/master/link.min.js

    0 讨论(0)
  • 2020-11-22 04:32

    Above answers clearly answer the question but I want to provide another alternative - A different view/approach to solve the similar problem.

    You can also use browser extension to remove X-Content-Type-Options response header for raw.githubusercontent.com files. There are couple of browser extensions to modify response headers.

    1. Requestly: Chrome + Firefox
    2. Modify Headers: Firefox

    If you use Requestly, I can suggest two solutions

    Solution 1: Use Modify Headers Rule and remove the response header

    Steps

    1. Install Requestly from http://www.requestly.in
    2. Go to Rules Page
    3. Click on Add Icon to create a rule
    4. Select Modify Headers
    5. Give a Name and Descripton
    6. Select Remove -> Response -> X-Content-Type-Options
    7. In Source field, enter Url -> Contains -> raw.githubusercontent.com

    Solution 2: Use Replace host Rule

    1. Install Requestly from http://www.requestly.in
    2. Go to Rules Page
    3. Click on Add Icon to create a rule
    4. Replace raw.githubusercontent.com with rawgit.com

    Check this screenshot for more details

    How to test

    We 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 script from raw github source.

    I also wrote an article on Requestly blog about this. Please refer it for more details.

    Hope it helps!!

    Disclaimer: I am author of Requestly So you can blame for anything you don't like.

    0 讨论(0)
  • 2020-11-22 04:32

    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

    0 讨论(0)
提交回复
热议问题