简体   繁体   English

在新标签页中打开链接后,与上一个标签页/窗口进行交互

[英]Interact with previous tab/window after opening link in a new tab

I have a spinner that shows on a page when a user submits a form. 当用户提交表单时,我有一个微调器显示在页面上。 If a user submits the form to a new tab though (control + click in Chrome) then the spinner in the original tab never goes away. 如果用户将表单提交到新标签页(在Chrome中按住Ctrl键并单击),则原始标签页中的微调框永远都不会消失。 How do I report back to the original tab once the new tab has completed loading so that the spinner will go away in that original tab and the user can interact with the page again? 一旦新标签页完成加载后,如何报告原始标签页,以便微调框将消失在该原始标签页中,并且用户可以再次与该页面进行交互?

I've tried researching articles and found one that says to prevent the user from opening in a new tab, however, I don't want to prevent them from doing that. 我尝试研究文章,并发现其中的一条内容是阻止用户在新标签页中打开,但是,我不想阻止他们这样做。 I want them to be able to open in a new tab. 我希望他们能够在新标签页中打开。

<form action="/Reports/Page1" id="reportForm" method="post">
...
<button class="btn rpcs-btn-primary" type="submit" formaction="/Reports/Page2">View Report</button>
</form>

I expect the user to be able to view the report in a new window/tab and once it loads, remove the spinner from the original window/tab. 我希望用户能够在新窗口/选项卡中查看报告,并且一旦加载,请从原始窗口/选项卡中移除微调器。

For as far as I'm aware different tabs in a browser don't share memory directly, so you can't access variables directly. 据我所知,浏览器中的不同选项卡不会直接共享内存,因此您无法直接访问变量。 You'd have to write some kind of workaround. 您必须编写某种解决方法。

A possibility, which I don't consider a good practice at all but would likely do the trick, would be to write a value to local storage (which any tab in the same domain can access) and read it periodically inside of a loop. 我根本不认为这是一种好的做法,但可能会解决问题的一种可能性是将值写入本地存储(同一域中的任何选项卡都可以访问)并在循环内定期读取它。

It would be something like: 就像这样:

When the form is submitted you do 提交表格后,您可以

localStorage.setItem("form_submitted", "true");

And when "on click" is triggered in the button 当按钮上触发“点击”时

let myInterval = setInterval(function(){
  if(localStorage.getItem("form_submitted") === "true") {
    // REMOVE SPINNER HERE
    clearInterval(myVar);
  }
}, 1000);

That way you can share some context between two tabs. 这样,您可以在两个选项卡之间共享一些上下文。 My opinion though is that you really should prevent your user from opening a new tab , so you would be able to use simple event-based logic instead of busy waiting. 不过,我的观点是, 您确实应该阻止用户打开新标签页 ,因此您将能够使用基于事件的简单逻辑,而不必忙于等待。

Note that local storage only accepts strings and any non-empty string is parsed to true in JavaScript, that's why I'm explicitly verifying if the value is equal to "true". 请注意,本地存储仅接受字符串,并且在JavaScript中任何非空字符串都被解析为true,这就是为什么我要明确验证该值是否等于“ true”的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM