In JavaScript, obtaining the URL of an iframe after it has been reloaded is not functioning correctly in Chrome and Safari browsers

I have been developing a phaser game that will be integrated into a website through an iframe. The game has the capability to support multiple languages, and we have decided to determine the language based on the site from which the game was accessed (for example, phaser-game.com/ru would display in Russian, phaser-game.com/ar would display in Arabic, etc).

Here is the current code snippet triggered by

window.addEventListener('load', getDomainSetLanguage);
:

function getDomainSetLanguage()
{
    let url = (window.location !== window.parent.location) ? document.referrer : document.location.href;
    console.log('url = ' + url);

    for (let i = 0; i < COUNTRIES_DOMAIN.length; i++)
    {
        if (url.indexOf(COUNTRIES_DOMAIN[i].URL) >= 0)
        {
            DOMAIN_ID = COUNTRIES_DOMAIN[i].ID;
            LANGUAGE_ID = COUNTRIES_DOMAIN[i].LANGUAGE_ID;
            break;
        }
    }

    if (DOMAIN_ID === -1)
    {
        DOMAIN_ID = 1;
    }

    if (LANGUAGE_ID === -1)
    {
        LANGUAGE_ID = 1;
    }

    console.log('DOMAIN_ID = ' + DOMAIN_ID + "; LANGUAGE_ID = " + LANGUAGE_ID);
}

While this implementation works well initially, there is a challenge when the game triggers a reload intermittently. Upon return, the game acquires its own URL instead of inheriting the parent's or iframe's URL.

As a result, the game default language switches to English.

It is worth noting that this issue only arises in Chrome and Safari browsers, with FireFox functioning correctly.

Is there something crucial that I might be overlooking? Any suggestions for alternative approaches?

I attempted to log the values of document.referrer and document.location.href, but encountered browser errors related to permissions, leading the game to revert to English as the default language.

In my research from here, I discovered that Chrome (and possibly Safari) may not trigger the onload function for objects within the iframe. However, given that other functions tied to onload are working fine, I am unsure if this explanation applies to my situation.

One important restriction is that I am unable to modify the iframe directly, so any resolution must originate from within the game itself.

Thank you!

Answer №1

const currentUrl = (window.location !== window.parent.location) ? document.referrer : document.location.href;

This particular line of code in your script is responsible for determining the URL based on whether the page is being viewed within an iframe or not. If it's inside an iframe, it uses document.referrer as the source URL.

According to the definition provided on the MDN Document.referrer page:

The Document.referrer property retrieves the URI of the webpage that linked to the current page.

When within an <iframe>, initially, the value of Document.referrer will match the href of the parent window's Window.location.

As you've observed, this functionality works well upon the initial load. However, discrepancies may arise during reloading as the browser behavior varies due to lack of explicit guidelines in the specification. It's reasonable to expect resetting to an empty value after a reload since it wasn't loaded from the parent page that time.


An alternative approach could involve using window.parent.location.href, which consistently refers to the URL of the parent window of the iframe. Further insights can be found in this discussion on the variance between document.referrer and window.parent.location.href.

You could adopt the following code snippet for achieving the same outcome:

// When the parent and child URLs align, utilizing either leads to identical outcomes
// In scenarios without a parent, window.parent equals window
// Consequently, the conditional check becomes surplus 
const currentUrl = window.parent.location.href;

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

MongoDB subfield pagination technique

I am looking to retrieve specific data from a sub-field in a MongoDB collection and implement pagination for it. Thank you! { "_id": "616d274c655e0000ee005f32", "subscription": [ { "account_admin&q ...

Using DIV to "enclose" all the elements inside

I need assistance with my HTML code. Here is what I have: <div id="cover" on-tap="_overlayTapped" class$="{{status}}"> <form method="POST" action="/some/action"> <input required id="name" name="name" label="Your name"></input> ...

Preserving alterations to media files using an image cropper

I've created a special controller for an image cropping tool that pops up over a media item in the content section. Right now I can manipulate the crops in the overlay, but when I click "Save Crops", the changes don't stick. However, if I use the ...

"Enhancing JqGrid functionality with inline editing and custom formatters

I'm currently working with a column model that looks like this: { name: 'CostShare', index: 'CostShare', width: 50, formatter: 'number', formatoptions: { decimalPlaces: 2, suffix: "%" }, resizeable: true, align: 'ce ...

Once a profile is added to the contact list, it fails to appear immediately. To see the new addition, the page must be manually refreshed, resulting in duplicate contact data being

Currently, there are three crucial files in play within this project. The primary one is index.js, responsible for running the server, while the other two are EJS files that need to be rendered. Despite numerous attempts to render and redirect these files, ...

Completely obliterate all charts when using the ngDestroy method in Angular 4

In this function, I am responsible for drawing the charts: private drawCharts(charts) { this.charts = charts.map((chart, i) => { this.options.title.text = chart.title; const options = { type: this.type || 'bar' ...

Tips for refreshing the page without losing the values of variables

In my simulation.jsp file, I have the following code that retrieves simulation data from a struts2 action: $(document).ready(function() { var data='<s:property escape="false" value="simInfos" />'; } Once I perform the simulation with this ...

Here's a guide on how to display texts underneath icons in Buttons using Material UI

Currently, this is the Button I have displayed https://i.sstatic.net/YkHp0.png I am trying to figure out how to position the Dummy Button text beneath the icon. Can someone assist me with this? Below is my code snippet: <Button className={classes.d ...

What is the best way to reduce the file size of a group of PNG images for

For my game character, I have a collection of PNG files including stand.png, run1.png, run2.png. To display a series of actions on the JavaScript canvas, I need to load these images. However, the size of each .png file adds up quickly – for example, it ...

Efficiently Incorporating JavaScript Variables into DataTable's aoData

I am facing an issue with a variable named search_gen, which is generated through an ajax request (shown below). var search_gen; $.ajax({ type: "POST", url: link+module_name+'search_generator/'+module_active, dataType: "text", as ...

Minimizing the gap between icon and label text

I have a React form that I need help with. The issue is that I want to reduce the space between the list icon and the label. Here is the CSS I am using: .form__container { display: flex; flex-wrap: wrap; } .form__container input { color: rgb(115, 0, ...

What is causing the "else" to activate in this particular if-else scenario?

I have implemented a method in Vue that toggles the darkMode variable when clicked. However, I'm facing an issue where it always triggers both the if and else parts of the method. data(){ return{ darkMode:false, } }, methods:{ darkMode ...

Can information be saved to a JSON file without using a server-side language?

Previously, I've come across questions where the recommended solution involves using a server-side language. However, since I don't have knowledge of a server-side language yet, I was curious to know if it's possible to achieve this with my ...

GSAP also brings scale transformations to life through its animation capabilities

I have an SVG graphic and I'm looking to make four elements appear in place. I've been using GSAP, but the elements seem to be flying into place rather than scaling up. Here's the code snippet I've been using: gsap.fromTo( ...

Arranging the Bars in a Bar Chart Using Chart.JS

Lately, I've been playing around with ChartJS and encountering an issue with sorting the bars in descending order, from lowest to highest. Despite my efforts to troubleshoot, I haven't had any success in resolving it. ...

What is the best way to ensure that the page reloads every time I access it

Creating a social networking website and working on a post edit page. However, encountering an issue when finishing editing the post and clicking 'SAVE EDIT'. I am using the code window.location='post_info.php?post_id='+postid; with AJA ...

Issues encountered when integrating a shader

I've created a shader and I'm trying to test it on Codepen. Despite having no errors in the console, the shader still isn't working as expected. Can anyone help me figure out what's going wrong? Below is my vertex shader: <script i ...

sending an array via xmlhttprequest

I am attempting to send all the marks entered by the user to another page for processing, but only the value of the first mark entered in the table is being sent. Is there a way to send all the values of the marks entered rather than just the first value ...

Mastering the concept of promise chaining through this straightforward example

I'm struggling to implement a logic where I need to compare the user's password to a given password and handle different scenarios based on the comparison result. Here's what I need to achieve: If the user doesn't exist, return undefi ...

margin-top: automatic adjustment, with a minimum of 50 pixels

I am trying to add a minimum of 50px margin to the top of my footer tag using CSS, but I haven't been successful with the min() function. I'm not sure if I am overlooking something or if there is another correct approach to achieve this. * { ...