What is the best way to ensure accurate URLs are sent to an iframe page?

My website supports URLs in the following formats:

(1) http://mysite.example.com/section/ - main page
(2) http://mysite.example.com/section/#page2
(3) http://mysite.example.com/section/surname-name-middlename/
(4) http://mysite.example.com/section/surname-name-middlename/#page2
(5) http://mysite.example.com/section/add

Currently, I am attempting to display my site within an iframe on another website. This external site allows me to use the setLocation and onLocationChanged methods to manipulate and respond to URL changes with hash tags.

I have successfully implemented the setLocation for all pages on the external site. Here is how the links above look on the third-party site:

(1) http://3rdpartysite.com/mypage
(2) http://3rdpartysite.com/mypage#page2
(3) http://3rdpartysite.com/mypage#surname-name-middlename
(4) http://3rdpartysite.com/mypage#surname-name-middlename,page2
(5) http://3rdpartysite.com/mypage#add

However, I am now facing a challenge with implementing the correct behavior for the onLocationChanged method.

The "section" part of the URL is consistent across all pages.

In trying to address this issue at the main page (excluding option 4 above), I have attempted the following:

// The location parameter corresponds to everything after the # in the URL: http://3rdpartysite.com/mypage#...
function onLocationChanged(location) { 
  if (location.indexOf('page') > -1) {
    window.location.href = '#' + location;
  } else if (location == 'add') {
      window.location.href = window.location.host + window.location.pathname + '/add';
    } else if (location != '') {
        window.location.href = window.location.host + window.location.pathname + '/' + location + '/';
      }
}

Despite these efforts, the functionality does not work as intended. What could be the issue with my approach?

Answer №1

Check out the code performing correctly on the main page:

function handleLocationChange(loc) {
    var currentURL = window.location.protocol + '//' + window.location.host + window.location.pathname;
    
    if (loc.indexOf('page') > -1 && loc.indexOf(',page') == -1) {
        window.location.href = '#' + loc;
    } else if (loc == 'add') {
        window.location.href = currentURL + 'add';
    } else if (loc != '' && loc.indexOf(',page') > -1) {
        window.location.href = currentURL + '' + loc.split(',', 2)[0] + '/#' + loc.split(',', 2)[1];
    } else if (loc != '') {
        window.location.href = currentURL + '' + loc + '/';
    }
}

And here is the code for other pages (without option (4) support):

function handleLocationChange(loc) {
  var currentURL = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname.split('/',3)[1] + '/';
  
  if (loc.indexOf('page') > -1) {
    window.location.href = currentURL + '#' + loc;
  } else if (loc == 'add') {
      window.location.href = currentURL + 'add';
    } else if (loc != '') {
        window.location.href = currentURL + '' + loc + '/';
      }
}

It's a bit tricky to unify these two codes.

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 ion-col with col-3 is causing a template parse error

Currently, I am facing an issue while trying to print data from a constructor. Everything is working fine until I added col-3 to ion-col. It seems like I missed including some module, but I am not sure which one. This is my home.ts file: import { Compone ...

Showing particular classes on an element using intersectionObserver/Scrollspy: a step-by-step guide

Here are three different sections on my Vue page. <section id="home">Home</section> <section id="about">About</section> <section id="contact">Contact</section> When I click on a Navbar Link ...

Ways to remove a dynamic field with jquery

I have developed a script that allows me to add dynamic fields and delete them as needed. However, I am facing an issue where I cannot delete the first element with the "el" class in my script because it removes all elements within the "input_fields_cont ...

Retrieve Items Using a Specific Value in JSON

What is the best method for filtering a JavaScript array of objects based on a specific key-value pair? For example: I am interested in selecting items by their color from the array below: [{Id:1, color:"blue"},{Id:2, color:"green"},{Id:3, color:"blue"}, ...

Is there a way for me to retrieve the data returned from a worker thread?

In my quest to understand how worker-threads function, I've come across this useful example: https://github.com/heroku-examples/node-workers-example.git REMINDER: Ensure Redis is installed and running for this example My primary challenge lies in r ...

Exploring the World of THREE.js: Particles and PointClouds

I am currently working on a project where I want to create orbiting objects with trails. To achieve this, I have set up a particle system using THREE Geometry, a THREE PointCloud, and a THREE PointCloudMaterial: particleMaterial = new THREE.PointCloudMate ...

Encountering a SyntaxError after deploying a Rails6 application: Unexpected token 'export' issue arises

After the most recent deployment, the application was functioning perfectly until it started displaying errors in Developer Tools and on every tab that is clicked within the application. The deployment process is carried out using Capistrano Uncaught Synt ...

Iterate through each image within a specific div element and showcase the images with a blur effect applied

I have a div with multiple images like this: <div class="am-container" id="am-container"> <a href="#"><img src="images/1.jpg"></img></a> <a href="#"><img src="images/2.jpg"></img>< ...

Automatically clear out table rows once the maximum row limit is reached, then append new data using the WebSocket data in JavaScript

Recently, I delved into JavaScript and faced a dilemma with my Bitcoin Price update dashboard. The data is streaming in through an external WebSocket, updating the prices every second. But here's the catch - the table rows are going crazy! To maintain ...

What is the solution to resolving the error "null property 'role' cannot be read"?

I'm encountering an issue whenever I enter the following code: if(message.member.roles.cache.has(`something here`)) An error is displayed stating "Cannot read property 'role' of null" Does anyone have any solutions or suggestions to resol ...

When you attempt to "add website to homescreen" on an iPhone, Ajax malfunctions

I have a unique website feature that utilizes ajax to dynamically load content when the user interacts with certain buttons. Everything functions smoothly up until a user tries to access the website through the "add to homescreen" option on mobile Safari a ...

Modify form content by utilizing a VueJS method

Currently, I am utilizing VueJS and facing a challenge with a form that consists of two fields. The first field requires user input, while the second field should calculate its value by passing the input from the first field through a method. HTML <di ...

Signal for a complete 360 degree rotation of an image

Looking to enhance my 360 image rotator with an indicator that fades out after the first image. I added this function to the end of my 360.js: (function(){ if( $('#first').css('visibility','hidden')) { $('#rotat ...

Sharing data from JavaScript to view in Rails: A step-by-step guide

After clicking the submit button, the controller renders with JSON data. The JSON data is {notes: array[1], array[2]}. The next step is to render the view.html.erb file. How can the values in notes be displayed like <%= notes %> in this file? ...

The object is given a value in the form of a string, even though it is a strongly-typed variable

I'm encountering something unusual in my code. In the following example, there is a (change) event that captures the current value selected by the user from a dropdown menu. <div style="padding-right: 0; width: 100%;"> <label st ...

Choose Default Value in Drop-Down List in AngularJS when Page Loads

Within the realm of Angularjs, there exists a DropDown: <select ng-model="category" ng-change="categoryChanged(category)" class="form-control" data-ng-options="category as category.name for category in categories"> <option value="">Se ...

Guide to setting up a backend system using AJAX, PHP, and MySQL to handle dynamic video sources in conjunction with Google TV Templates

If you're looking to develop web apps for Google TV, particularly those involving video content, the simplest method is to utilize Google TV Templates: https://developers.google.com/tv/web/docs/gtv-templates. The original Google TV Templates included ...

Prevent user input in Vue.js until the value has been modified

Need help handling initial input values: <input type="text" v-model="name" ref="input" /> <button type="submit" :disabled="$refs.input.defaultValue == $refs.input.value">Submit</button> Encountering an error with the disabled binding: C ...

Is there a way to show several elements simultaneously by hovering over another?

Can anyone help me with setting display:block; on all the p tags and the overlay div when I hover over my img tag? Is this achievable with just CSS or do I need to incorporate some JavaScript? Open to suggestions on the best approach. Any assistance woul ...

Having trouble compiling your React app after adding 'node-sass'? Here's how to resolve the "Module not found" error

After successfully building a react.js app, I encountered an issue upon installing 'node-sass' using npm install. While the app works seamlessly in the production build, it fails to compile in the development build when using npm start. Surprisi ...