Can a JavaScript hosted on different domain read/modify DOM of another domain?

后端 未结 2 380
南笙
南笙 2021-02-06 04:07

I have a question regarding a potential security issue/limitation regarding JavaScript hosted on a domain (ex: domain of a CDN, say example.com), but loaded from a website under

2条回答
  •  迷失自我
    2021-02-06 04:36

    Isn't this a possible security issue?

    Yes, this is called Cross-Site-Scripting (XSS).

    It is most definitely a security issue.

    Bottom line, never include code, from any domain, that you don't trust. End of story.

    If an attacker can get code running on your domain, it's game-over.

    Shouldn't this trigger the same-origin-policy protection?

    No.

    The same-origin-policy basically means that the script can only ever view/modify the DOM of the domain to which it was loaded. So you can't create an iframe to an arbitrary site and read that DOM from the parent unless CORS is on, or your script is running there too.

    Perhaps, are there user agents that prevents a Javascript, hosted on a different domain, to access elements in the page that executes the script?

    The only way to do this, is to sandbox that javascript inside of an iframe which is on a different domain.

    So you could create a sandbox.example.com domain, which generates a wrapper page which includes the javascript.

    Then, instead of linking to the JS directly, create an iframe to the sandbox domain. The JS will have access to that domain, and everything in that DOM, but nothing outside of the iframe.

    You still have to be careful to set cookies properly (don't do wildcard domains, etc). But it can help.

提交回复
热议问题