Search code examples
javascriptbrowsersame-origin-policy

If JSONP easily works around cross domain constraints, why do browsers even bother anymore?


If JSONP easily works around cross domain constraints (same origin policies), why do browsers even bother anymore? I'm racking my brain for a reason, but all I come up with is that it's actually worse and provides an illusion of safety.


Solution

  • The reason is simple, it bases on TRUST. If there is no trust, you cannot do JSONP. For example: if domain abc.com does not trust def.com, abc.com just does not support JSONP and def.com cannot utilize JSONP (or CORS).

    Both server and client have to trust each other for JSONP to work (including CORS)

    • The server trusts the client and supports JSONP (CORS)
    • The client trusts the server that the script returned from the server does not compromise javascript on the page. Because in order to use JSONP, the client loads the script and execute it using script tag => very dangerous.

    When you implement your code, usually both domains are under your control and there is no harm doing that. In other cases, for example yourdomain.com and evil.com do not trust each other => browsers block cross-domain requests to ensure security.

    JSONP easily works around cross domain constraints

    No, you cannot always use JSONP. JSONP only works if there is trust between browser and server.