sailei1 / blog

1 stars 0 forks source link

同域下,多iframe 页面 借助localStorage 传递参数 #115

Closed sailei1 closed 2 years ago

sailei1 commented 2 years ago
window.addEventListener('storage', function (e) {
if (e.key == 'openPage') {
        const { url = '', name, menuId } = JSON.parse(e.newValue);
        localStorage.removeItem('openPage');
        addPerson({ url, name, menuId, type: 'page' });
      }
    });
// 刷新
window.addEventListener('beforeunload', (e) => {
      sessionStorage.setItem('refresh', true);
    });
export const openPage = (paramData, useIframe = false) => {
  // debugger;
  console.log(process.env);
  let pageObj = {
    path: '',
    text: '新开页面',
    mid: new Date().getTime(),
    param: {},
    // http: location.origin + '/#',
    http: OPENURL,
  };
  pageObj = Object.assign(pageObj, paramData);
  let urlParam = '';
  // for (var key in pageObj.param) {
  //   if (pageObj.param[key]) {
  //     urlParam += key + '=' + pageObj.param[key] + '&';
  //   }
  // }
  const { mid, text, http, param, path } = pageObj;
  let url = path;
  const pKeys = Object.keys(param);
  for (let i = 0; i < pKeys.length; i += 1) {
    if (param[pKeys[i]]) {
      urlParam += `${pKeys[i]}=${param[pKeys[i]]}&`;
    }
  }

  if (urlParam) {
    url = `${http}${path}?${urlParam.substr(0, urlParam.length - 1)}`;
  } else {
    url = http + path;
  }
  console.log(url, paramData);
  if (!useIframe) {
    const menu = {
      menuId: `${mid}`,
      path: `/dynamic/${mid}`,
      name: text,
      url,
    };
    localStorage.setItem('openPage', JSON.stringify(menu));
  } else {
    try {
      if (window.parent && window.parent.qdLayout) {
        window.parent.qdLayout.openPage(mid, text, url);
      } else {
        window.open(url, '_blank');
      }
    } catch (e) {
      console.log(`openPage异常:${e}`);
      window.open(url, '_blank');
    }
  }
};
// 调用
openPage(
                {
                  path: 'xxx',
                  text: 'text',
                  param: { id: record.id || '', isDetail: true },
                },
                true,
              );