前端一些不常用知识记录

1. 获取用户进入当前标签页或者离开标签页事件

document.addEventListener('visibilitychange', function() {
    if (!document.hidden) {
        console.log('你又进来啦?');
    } else {
        console.log('你要离开啦?');
    }
})

2. iframe实战,postMessage参数的传递

  a.  子页面向父页面传参
// 子页面传递
const parentWindow = window.parent.window;
parentWindow.postMessage('success: child message!', '*');

// 父页面接收
window.addEventListener('message',function(response){
  const postData = response.data;
  console.log(postData, '<=== child msg'); // success: child message!
});

 

  b.  父页面向子页面传参

 1 // 父页面传递
 2   const childAddress = 'http://127.0.0.1:8080';
 3   const iframe = document.getElementById('iframe');
 4   iframe.contentWindow.postMessage('success: parent message!', childAddress);
 5 
 6   // 子页面接收
 7   const parentAddress = 'http://128.0.0.1:8080';
 8   componentDidMount() {
 9     window.addEventListener('message', this.onListenerPostMessage);
10   }
11   componentWillUnmount() {
12     window.removeEventListener('message', this.onListenerPostMessage);
13   }
14   
15   onListenerPostMessage = (response) => {
16     const postData = response.data;
17     const origin = response.origin || response.originalEvent.origin;
18     if (origin !== parentAddress) { // 过滤
19       return;
20     }
21     console.log(postData, '<=== parent msg'); // success: parent message!
22   };

 

posted @ 2018-08-29 14:10  刘haha  阅读(257)  评论(0编辑  收藏  举报