Background. I am working in Firefox. I am creating a documentation page with example queries (as hyperlinks) to my Apache Solr instance, running in the background.
Issue. I have found that when I send queries to Solr via hyperlinks (not an input element) I need to (1) let that search page load; (2) then execute the query.
Additionally, I have found that the named page (window / tab) that I reuse for the example queries needs to be focused to work correctly.
Hence, I (1) open the search page; (2) wait for that page to fully load, then open the query URL.
I have created a minimal example to show the issue, with a call to example.com in lieu of my search page (1., above); then after a time, the call to the the second URL (Google or Bing, in lieu of the search query in 2. above).
I believe the issue is related to the last sentence in the accepted answer here:
check if a browser tab is already open so I don't make extra tabs
... once the user refreshes the page, that reference is lost.
In my code, if I use
my_window = window.open("", "my_tab");
then the setTimeout()
executes, prints to console.
If I use
my_window = window.open("", "my_tab").focus();
then (per the StackOver flow link above) I believe that the my_window
object is lost, hence the setTimeout()
never executes.
Question: how can I persist the named window / tab object (my_window
)? localStorage
? ...
JSFiddle: https://jsfiddle.net/vstuart/1yfeqkz9/8/
<html lang="en">
<head>
<script>
function foo(obj) {
globalThis.link = (obj.getAttribute("href"))
console.log('[foo] link:', link);
// ISSUE HERE:
// my_window = window.open("", "my_tab").focus();
// SOLUTION HERE, per accepted answer, below:
my_window = window.open("", "my_tab");
my_window.focus()
my_window.location = "https://example.com/";
setTimeout("bar(link)", 2000);
return false;
}
function bar(link) {
console.log('[bar] link:', globalThis.link);
my_window.location=globalThis.link;
}
</script>
</head>
<body>
<ul>
<li><p><a target="my_tab" onclick="foo(this); return false;" href="https://dogpile.com/">Dogpile.com</a></p></li>
<li><p><a target="my_tab" onclick="foo(this); return false;" href="https://duckduckgo.com/">DuckDuckGo.com</a></p></li>
</ul>
</body>
</html>
You can call .focus()
on the line following the assignment.
my_window = window.open("", "my_tab")
my_window.focus()
When you use
my_window = window.open("", "my_tab").focus();
the problem is that my_window gets assigned the return value of focus, not the return value of window.open.