[SOLVED] Opening a url in a browser tab only works in the editor

Hi

In our game we have the functionality to click on Links in the UI and they open in a new browser tab.
This works great when we test the game via the launch button of the editor.
However if I publish the game and upload it to our own server the code throws an exception saying

TypeError: Cannot read properties of undefined (reading ‘open’)

The code to open the window is nothing special

this.entity.element.on('click', function (evt) 
    {
        var win = window[1].open(link,'_blank');
        this.text.element.color = this.visitedLinkColor;
        evt.stopPropagation();
        console.log('The element ' + evt.element.entity.name + ' was clicked.');
    },this);
};

Debugging show that when launching the game via the editor the window object has an array with 2 Elements in it.
On our own server however the window object does not have an array.

Editor:
Editor

Our Server:
Build

Any ideas what might be causing this or how to fix it?

Thx in advance!

Hi ,

window object is global.So ,

window.open(link, '_blank').focus();

Above code works well for published projects

Hi,

thx for the suggestion but I get

window.open is not a function

It seems like window gets redefined somehow but I have no clue why or how.

Do you have demo/link of this? That looks like your window global is being redefined somewhere

Hi,

sorry for the late reply but I was on vacation :smiley:

A simple repro case can be found here Gruene Gase

Clicking on the start button should open a url (in this case just google.com) in a new tab.

The project is build without minification etc. so you can debug it properly if you want.

Thx

That project is still using window[1].open which isn’t part of API for the window object.

The only reason it’s working in the launch tab is because something else that PlayCanvas site is loading is adding those properties to the global window object (maybe analytics or something else)

Use window.open instead.

This is because all global variables are added to the window object.

So this code here

Sidepanel.attributes.add('selectionMarker', {
    type: 'entity'
});

var open = false;
var selectedClusterID = "";

Both open and selectedClusterID become accessible as window.open and window.selectedClusterID as they are declared in the global namespace

Which is why window.open is no longer a function when you try to call it.

Try to avoid global variables like this for this reason. Scope them in another object that you know doesn’t clash with the window API.

eg

Sidepanel.open = false;
Sidepanel.selectedClusterID =  "";

Or even better, not have globals at all if you can help it.

1 Like

Thx for the super fast and indepth reply!
This happens when a c# dev tries to use javascript :smiley:

1 Like