Why is cross-domain JSONP safe, but cross-domainJSON not?

前端 未结 2 745
庸人自扰
庸人自扰 2021-02-01 04:01

I\'m having trouble connecting some dots having recently learned of JSONP. Here\'s my understanding:

  • Cross-domain XmlHttpRequests for any content (including JSON)
2条回答
  •  广开言路
    2021-02-01 04:24

    I understand this question to be about why the browser considers JSONP safe, not about whether it is safe (which it isn't). I will address this question step by step.

    Regular ol' AJAX

    To perform a regular AJAX request, the browser creates an XHR object, points it at the URL and pulls the data. The XHR object will only trust data from the same domain. This is a hard limitation. There is no getting round it in current browsers (edit - you can now use CORS).

    Solution - Don't use XHR

    Since XHR is subject to the same domain poilicy, we can't use XHR to do cross domain AJAX. Luckily, there are other ways to hit a remote server. We could append an image tag to the page for example. We can also append a script tag and give it a src attribute that points to the remote server. We can pull JQuery from a CDN for example and expect it to work.

    How JSONP works.

    When we make a JSONP request, our code dynamically appends a script tag to the page. The script tag has a source attribute which points to the remote JSONP API url, just as though you were inserting a script from a CDN.

    The JSONP script returned by the server is wrapped in a function call. When the script is downloaded, the function will be executed automatically.

    This is why we have to tell the JSONP the name of the callback function we want to wrap the script in. That function will be called once the script has downloaded.

    Security concerns

    There are some fairly big security concerns here. The script you are downloading could take control over your page and put your users at risk. JSONP is not safe for your users, it is just not blocked by the web browsers. JSONP really is a browser exploit which we are taking advantage of. Use with caution.

    Used wisely, JSONP is pretty awesome though.

提交回复
热议问题