首页 > 解决方案 > 在 window.open 之后 - 清除新的 windows localStorage 并重新加载它

问题描述

我有类似逻辑的预览,您可以在其中通过 window.open() 预览 HTML 页面中的更改并能够登录等,但问题是我想确保仅在窗口上清除新的 Windows 本地存储,因此每次打开新的预览窗口时都需要登录。

因为在执行代码以打开新窗口的门户中维护会话所需的数据 - 如果我运行 localStorage.clear(); 这意味着每次打开该窗口时都需要在门户和窗口中登录 - 这是我不想做的事情,我只想确保仅新打开的窗口需要登录。

我已经在这里研究了各种方法来处理这个问题,但到目前为止我还没有感到高兴。

实际上,我想做的是以下几点:

  1. 打开窗户。
  2. 清除本地存储。
  3. 重新加载窗口。

我拥有的一些代码的示例如下:

  return setInterval(() => dispatch(getPreviewStatus(requestData)).then(res => {
    if (res[dataPreview.propertyNames.status] === dataPreview.status.completed) {
      const windowFeatures = 'location=yes,scrollbars=yes,status=yes';
      let window = window.open("www.testing.com", '_blank', windowFeatures);
      let preview = window.open(URL, '_blank', windowFeatures);
      let script = document.createElement('script');
      script.textContent = 'alert(\'JS is running\');';
      preview.document.head.appendChild(script);
    }
  }), 5000);

是否可以通过 window.open 来完成此操作-我确实在这里尝试了最佳解决方案:Running Javascript in new window.open但没有运气-这是我尝试过的 script.textContent = 'localStorage.clear(); location.reload();';

非常感谢!

编辑 1:我在调用它的同一个域中打开窗口。

编辑 2:我正在打开窗口并可以执行警报 - 但如果尝试清除localStorage.clear();它会清除打开窗口的页面并且location.reload();不会重新加载窗口。

标签: javascript

解决方案


当您打开一个新窗口时,返回值是对新窗口的引用。这意味着您可以在该窗口上访问本机功能。例如,您可以运行

  const windowFeatures = 'location=yes,scrollbars=yes,status=yes';
  let win = window.open("www.testing.com", '_blank', windowFeatures);
  console.log(win.localStorage);
  win.localStorage.clear();
  console.log(win.localStorage);
  win.location.reload();

As you can see, I'm asking to access the local storage and the location of the window we opened. If you were to copy these lines and run them in the developer tools of the browser, you would see them in action.

Note that you'are already doing this to insert the script that runs the alert.

preview.document.head.appendChild(script);

Note also that in your code, you used the name 'window' which is a reserved word.


推荐阅读