JavaScript 跨域通讯

2021-06-01 09:44 更新

1.5.1【必须】使用安全的前端跨域通信方式

  • 具有隔离登录态(如:p_skey)、涉及用户高敏感信息的业务(如:微信网页版、QQ空间、QQ邮箱、公众平台),禁止通过document.domain降域,实现前端跨域通讯,应使用postMessage替代。

1.5.2【必须】使用postMessage应限定Origin

  • 在message事件监听回调中,应先使用event.origin校验来源,再执行具体操作。

  • 校验来源时,应使用===判断,禁止使用indexOf()

  1. // bad: 使用indexOf校验Origin值
  2. window.addEventListener("message", (e) => {
  3. if (~e.origin.indexOf("https://a.qq.com")) {
  4. // ...
  5. } else {
  6. // ...
  7. }
  8. });
  9. // good: 使用postMessage时,限定Origin,且使用===判断
  10. window.addEventListener("message", (e) => {
  11. if (e.origin === "https://a.qq.com") {
  12. // ...
  13. }
  14. });
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号