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

The accordion seems to be stuck in the open position

Working on a website, I encountered a frustrating bug with an accordion feature. When clicking on the arrow, the accordion opens and closes smoothly. However, when attempting to close it by clicking on the title, the accordion bounces instead of closing p ...

React JS does not allow TextField and Select to change

I am relatively new to full stack development and I am currently working on a project to enhance my understanding of frontend development with React JS. While working on this project, I have been using Redux without any issues so far. However, I am facing ...

What could be the reason for Safari generating larger videos than Chrome when utilizing the MediaDevices.getUserMedia() API?

Embarking on a small experiment to gauge the size of captured videos using the MediaDevices.getUserMedia() API. My Safari implementation yielded videos 5-10 times larger than those in Chrome. Here's the code snippet: index.html: <html lang=" ...

tips for converting objects into arrays with JavaScript

I have an object and I would like to convert it into an array const object1 = { a: { hide:true}, b:{} }; I am currently using Object.entries to perform the conversion, however, I am struggling with understanding how it should be done. Object.entries ...

A guide on accessing JavaScript files from the components directory in a React Native iOS application

I am encountering difficulty in accessing the components folder within my React Native Project on IOS. The error message I am receiving is: Unable to resolve module ./Login from ....../ReactNative/ReactNativeProject/components/App.js: Unable to find ...

What is the best way to utilize the sx prop in Material UI for applying styles specifically when the component is active or selected?

In the code snippet below, I have set up the useState hook so that when a ListItem is clicked on, the selected state becomes true. My goal is to apply specific styling when an item is selected using the sx prop instead of creating a styled component for su ...

Modifying the chart width in Chart.js: A step-by-step guide

After creating a chart using Chart Js, I encountered an issue where the chart did not fit within the specified width. Adjusting the attributes of canvas proved to be ineffective, specifically with regards to the width attribute. Despite changing the value, ...

WordPress REST API - Issue with New Category returning undefined, yet still able to be accessed

Currently, I am utilizing the WordPress REST API and have successfully created a new category. However, when making queries to the API, it is returning undefined for that particular category. Upon visiting: /wp-json/wp/v2/categories, category 17 does not ...

Utilizing .isDisplayed() in conjunction with .each() in ProtractorJS for Angular: A guide

Currently, I am working on setting up a test within my Angular application. The goal of this test is to click on an element and check if a specific object is displayed. While I believe the code provided below should work, I am aware that the isDisplayed( ...

Step-by-step guide to utilizing instance functions in AngularJS

Recently I started working with angular in my project but I'm struggling to figure out how to access instance functions from the original code. Here is a snippet of my function: $scope.collapsedrow = true; $scope.PlusClick = function(event) ...

Choosing just the element that was clicked and added to the DOM

I've been experimenting with JQuery in a web app I'm developing. The app involves dynamically adding elements to the DOM, but I've encountered an issue with click events for these newly added elements. I'm looking for a way to target an ...

Leveraging the power of Express.js, transmit local data alongside a

Why can't I display the active user in my view using plain HTML when console log shows it? Here is the code snippet: app.post('/', function (req, res) { var user = { user : req.body.username }; res.render('doctor_hagfish/pets&ap ...

html form submission error - please refresh

After submitting a form on my page, I keep encountering an error every time I try to refresh the page. I've attempted several solutions that I came across online, but none of them have resolved the issue as I continue to face this error on different ...

Integrate a feature in React-native MapView that dynamically swaps out markers with different images

Thanks to the insights shared in this informative article, I successfully integrated observations into my MapView. mapMarkers = () => { return this.state.items.map((item) => <Marker key={item.id} coordinate={{ latitude: item.g ...

The progress bar in Java Script is static and cannot be customized to change colors

Trying to use HTML for image uploads and I've created Java code to monitor the progress of the upload. However, I'm facing an issue where I cannot change the color of the progress loading bar. Below is the code I am currently using for uploading ...

Every time $injector.get is invoked, it triggers the run() method of the Angular module

I find myself in a situation where I need to manually retrieve objects from the Angular $injector. Up until now, I have been using the following approach: var injector = angular.injector(['app.service', 'ng']); var myService = injecto ...

What is the reason for jQuery scripts not functioning properly when the scripts are placed above the jQuery library?

this script is functioning correctly: <div class="demo-gallery" data-pswp-uid="1"> <a class = "delete_button">click</a> <script src="https://code.jquery.com/jquery-2.1.4.js"></script> <script> ...

Issue with Bottle.py: When using AJAX, request.forms.get() is returning NoneType

Having trouble sending JavaScript data to a bottle.py server using AJAX? Despite trying numerous solutions from various sources, none seem to be working. To provide clarity, I'm focusing on the AJAX call code here. Can someone explain why request.for ...

combining all JavaScript script tags into a single tag

I'm currently working with wavesurfer.js and have the following setup: 'use strict' <!-- wavesurfer.js --> <script src="src/wavesurfer.js"></script> <script src="src/util.js"></script> <scrip ...

The webpage encountered an issue while trying to load a resource: the server returned a 500 (Internal Server Error) status message, preventing the submission of the data

When I use AJAX jQuery to send data via POST, the input name does not get sent and the database shows NULL as the answer. Thank you for any assistance. Below is my JQuery code: $('#btn-save').click(function(){ $.ajax({ url: "<? ...