open a new window with a reference based on the name

In order to obtain a reference to the currently open window, I utilize the following code:

var refWindow = window.open("mypage1", "name_mypage");

If I wish to close the window, I simply use this command:

refWindow.close();

When I refresh the screen (by pressing F5) and execute the same line of code, the new content opens in the existing window since I have specified the same name.

var refWindow = window.open("mypage2", "name_mypage");

However, it is crucial to note that this creates a different reference (refWindow).

My question is: how can I assign a reference to the window based on its name? I need to close the current window before opening a new one with the same name.

One potential solution could involve performing the following steps:

var refWindow = window.open("about:blank", "name_mypage");
refWindow.close();
refWindow = window.open("mypage2", "name_mypage");

I am seeking an alternative method that achieves the desired outcome without requiring a blank window as a reference point.

Thank you.

Answer №1

After reviewing andres's feedback, here is the exact solution he is seeking:

refWin.location = "myurl";
refWin.focus();

This code snippet will launch "myurl" in a new window and give it focus.

Alternatively.

var refWin = window.open("mypage1", "name_mypage");
refWin.focus();

Update:

If you do not need to refresh the page, you could simply implement this approach:

var refWin = window.open("mypage1", "name_mypage");
refWin.close();
refWin = window.open("mypage1", "name_mypage");

If you are concerned about reliability, you might consider creating your own "windows" object:

var windows = {};
var refWin = window.open("mypage1", "name_mypage");
windows[refWin.name] = refWin;
windows("name_mypage").close();  // close the window

In my opinion, this method may not be very efficient since focusing the window may still present challenges, but it could possibly suit your specific needs.

Answer №2

the solution I came up with, inspired by a different script:

Helper.browser = new function () {

    // Local variables
    var window = window, screen = screen, _self = this, windows = {}, isChrome = /chrome/.test(navigator.userAgent.toLowerCase());

    // Public Functions
    this.focus = function (win) {
        if (!win) return;
        if (isChrome) win.blur();
        win.focus();
    };

    this.windowExists = function (winType) {
        return winType && windows[winType] && typeof windows[winType]['closed'] != 'undefined' && !windows[winType].closed;
    };

    this.close = function (winType) {

        if (typeof windows[winType]['close'] !== 'undefined') windows[winType].close();
        windows[winType] = null;

        return _self;
    };

    this.properties = function (props) {

        props = (props || 'menubar=yes').toLowerCase();

        if (!(/menubar/.test(props)))
            props += ',menubar=yes';

        if (!(/location/.test(props)))
            props += ',location=yes';

        if (!(/width/.test(props)))
            props += ',width=' + (screen.availWidth - 150);

        if (!(/height/.test(props)))
            props += ',height=' + (screen.availHeight - 150);

        if (!(/scrollbars/.test(props)))
            props += ',scrollbars=yes';

        if (!(/resizable/.test(props)))
            props += ',resizable=yes';

        return props;
    };

    this.open = function (url, winType, props) {

        if (_self.windowExists(winType))
            return _self.close(winType).open(url, winType, props);

        var urlToOpen = '';
        if (typeof url == 'string') {
            urlToOpen = url;
        } else if (jQuery(url).get(0).tagName.toLowerCase() == 'a') {
            urlToOpen = jQuery(url).attr('href');
        } else {
            urlToOpen = 'about:blank';
        }

        props = _self.properties(props);
        winType = winType || "_blank";

        var newWin = props ? window.open(urlToOpen, winType, props) : window.open(urlToOpen, winType);

        if (newWin && "_blank" !== winType) {
            windows[winType] = newWin;
            _self.focus(newWin);
        }

        return newWin;
    };

};  

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is causing setTimeout to not function as intended?

I'm having some trouble moving a <div id="box"> whenever my mouse hovers over it. Currently, the element only moves when I trigger the mouseover event on the div itself instead of when my mouse is actually hovering over it. document.getElements ...

Obtain a masterpiece by creating a canvas in React

Greetings! I have developed a drawing app using react and I am looking for a way to capture what the user has drawn on the canvas when they release the mouse button. This process should repeat continuously until the user stops drawing. Can anyone suggest h ...

Exploring the applications of the `this` keyword within a jQuery-based JavaScript object

Recently, there has been a challenge in creating a JavaScript object with the specific structure outlined below: function colorDiv(div){ this.div=div; this.div.bind("click",this.changeColor) this.changeColor(){ this.div.css(" ...

Issue with pushing inner list<object> in Knockout version 3.2.0

Currently, I am working with knockout.js on an ASP application. The issue I am facing involves a list of objects returned by the controller action to the view, where the objects in the list point to another list of objects. My struggle lies in adding new o ...

Is there a bug in Safari 8.0 related to jQuery and backslashes?

I am using Mac OS 10.10 Yosemite and Safari 8.0. Attempting to read an XML (RSS) file: <content:encoded>bla bla bla</content:encoded> The Javascript Ajax method I am using is: description:$(valeur).find('content\\:encoded&apo ...

Using jQuery to trigger an event when an element is empty or when the element contains children nodes

Is there a way to create a jQuery script that can monitor the children of an element? If the element does not have any children, default scrolling for the entire page is enabled. If the element has children, scrolling for the whole page is disabled. The ...

Investigating Jquery Flip Card Issues

Looking to create a set of flip cards using HTML, CSS, and jQuery. Currently facing an issue where only the first card is flipping when clicked. Any suggestions on how to modify the jQuery code to make it work for all cards would be highly appreciated. C ...

Troubleshooting the Gutter Problem in jQuery Isotope and Masonry

Currently, I am utilizing the Isotope jQuery plugin. While it is a fantastic tool, I am encountering a minor issue with aligning items in masonry mode. The width of my container is 960px, and I aim to have 4 items perfectly aligned as if they were adhering ...

Real-time Updating of ChartJS Charts in Rails Using AJAX

I am currently working with Rails 5 and the latest version of ChartJS library (). My goal is to retrieve the most recent 20 items from the SensorReading model and update the Chart using setInterval and AJAX. I have successfully created the AJAX call and ...

Tips for implementing resizable Material-UI Dialogs

I'm working on a project that involves creating a dialog box that can be resized and dragged. While I found steps in the Material-UI Dialog documentation on how to make it draggable, I'm still looking for information on how to make it resizable. ...

Limit the character count in a textarea

My goal is to control the number of characters that can be entered into a textarea. While I am aware that I could simply use a substring to limit the characters, I prefer to visually inform the user when their text has reached the maximum length. The maxl ...

Issue with a Jquery toggleClass function not working properly on hover

Hello everyone! I am a newbie in the community and relatively new to the world of web programming. I am encountering an issue that is really frustrating me. I attempted to use this code to add a class when hovering over the ul list element so that I can d ...

Tips for dynamically updating values when input numbers are modified using JavaScript

Check out this amazing tip calculator on netlify. I successfully built it using html, scss, and javascript without relying on any tutorials. Despite taking longer than expected due to being a beginner, I am proud of the outcome. Now, I need some assistanc ...

What is the most effective way to determine which radio button is currently selected in a group with the same name using JQuery?

<form class="responses"> <input type="radio" name="option" value="0">False</input> <input type="radio" name="option" value="1">True</input> </form> Just tested: $('[name="option"]').is(':checked ...

Having difficulty deleting a checkbox element using JavaScript

My goal is to have a feature where users can effortlessly add or remove checkbox div elements as needed. The code I have written successfully adds and resets checkboxes, but I am encountering an issue when trying to remove them. I am struggling to identif ...

Azure experiencing issue with MUI Datepicker where selected date is shifted by one day

I have developed a unique custom date selection component that utilizes Material UI and Formik. This component passes the selected date value to a parent form component in the following manner: import React from 'react'; import { useField } from ...

What is the reason behind the failure of next/script with Google reCAPTCHA?

Currently, I am in the process of upgrading from next js version 8 to version 11. I wanted to take advantage of the amazing next js feature for "next/script". However, when I tried to implement it for Google reCAPTCHA using "react-recaptcha": "^2.3.10", th ...

Searching through the Symfony2 database with the help of Select2 and Ajax

Currently, my FAQ System is running smoothly. However, I am looking to enhance it by adding a search function using Select2. Here's what I have so far: Select2 AJAX Script <script> $("#searchall").select2({ ajax: { ...

The dynamic Vue.js transitions and effects are like a magic

I am using a v-for to render multiple child components: <div v-for="(pass) in scoringPass" :key="pass.decision"> <Pass :pass="pass"/> </div> Each of these child components contains a transition tag: &l ...

Acquiring information to display in a div using innerHTML

I aim to create a div that displays different animal sounds, like: Dog says Bark Bark I've attempted various methods but I'm unable to get each pair in the array to show up in a div: const animal = [ {creature: "Dog", sound: "B ...