需求

需要在当前页面使用微信等第三方授权,在授权完成后,关闭授权窗口后,系统当前页面响应。

image.png

相关Api

  1. window.open
  2. window.opener
  3. postMessage

相关代码demo

Vue

  1. <script>
  2. let win;
  3. export default {
  4. ...
  5. mounted() {
  6. if (window.opener) {
  7. window.opener.postMessage(data, window.location.hostname);
  8. }
  9. window.addEventListener(
  10. 'message',
  11. e => {
  12. if (e.data) {
  13. setTimeout(() => {
  14. win.close(); 关闭新窗口
  15. win = null; // 关闭窗口后,释放内存
  16. }, 1000);
  17. // todo
  18. }
  19. },
  20. false,
  21. );
  22. },
  23. methods: {
  24. onOpen() {
  25. win = window.open(data, '_blank', 'top=200px,width=800px,height=600px');
  26. }
  27. }
  28. }
  29. </script>