Get a parameter from URL and add it to iframe src - javascript

I am looking for a simple way (using JavaScript) to get part of the page URL to be added to the end of the iframe src URL.
Example, page URL: www.example.com/?id=XYZ
Then I need the XYZ part, which is the the ID to be added to the iframe src like so:
And iframe src: www.otheradress.com/XYZ

You can get the query string from your route with window.location.search (only what comes after the '?', included), and you can parse the parameters with the URLSearchParams like this const params = new URLSearchParams(window.location.search);.
After that, params is an object with specific methods, and you can obtain your param by name with params.get('id');.
So you only need to concatenate your base URL and this parameter and pass it to the src attribute of the iframe.
Complete example:
const baseIframeUrl = 'www.otheradress.com/';
const urlParams = new URLSearchParams(window.location.search);
document.getElementById('#yourIframe').src = baseIframeUrl . urlParams.get('id');
If you wanted to use the src attribute from the HTML, it would be:
const urlParams = new URLSearchParams(window.location.search);
document.getElementById('#yourIframe').src = document.getElementById('#yourIframe').src . urlParams.get('id');
Though be aware that this approach would fail when called multiple times unless you store somewhere the original URL.
Also, as pointed out by mplungjan, you cannot access the src of an iframe of another origin.

I would use URL and URLSearchParams
NOTE: You cannot READ the iFrame src from an iframe that has loaded a page from another origin for security reasons
const url = new URL("https://www.example.com/?id=XYZ"); // new URL(location.href);
const id = url.searchParams.get("id")
console.log(id)
const iFrameUrl = new URL("https://www.otheradress.com/")
iFrameUrl.pathname+=id;
console.log(iFrameUrl.toString()); // here you can set the source of the iFrame

Related

urlSearchParams not updating the url

I am trying to add search and page to my url for searching and pagination on a page.
const urlParams = new URLSearchParams(window.location.search);
if(!urlParams.has('search'){
urlParams.append('search', question);
}
if(!urlParams.has('page'){
urlParams.append('page', pageIndex);
}
This appears to do nothing to the actual url.
But when I call urlParams.toString()
then I can see that they have been added, but they are not in the actual url in the browser.
I'm using Chrome 107, so it should support it.
Am I missing something?
The documentation has not helped me so far.
Of course it does nothing with the actual URL, you are creating a URLParameters Object and updating it. what you are missing is:
window.loacation.search = urlParams.toString()
it will change the query string in the browser URL and reloads the page.
if you are not interested in reloading the page, you can use history DOM object
let url = new URL(window.location.href);
if(!(url.searchParams.has('search'))){
url.searchParams.append('search', question);
}
if(!(url.searchParams.has('page'))){
url.searchParams.append('page', pageIndex);
}
history.pushState({},'',url.href);
finally, if you want to update the page and search params anyway, you can use the url.searchParams.set() method, like:
url.searchParams.set('page', pageIndex);
it will append the parameter if it does not exist, and will update it if it does, without throwing exceptions.
You can try this way:
First, retrieve the current path. Then, append the urlParams to the retrieved path and use history.pushState() to set the new URL.
const question = "the question";
const pageIndex = 3;
const urlParams = new URLSearchParams(window.location.search);
if (! urlParams.has('search')) {
urlParams.append('search', question);
}
if (! urlParams.has('page')) {
urlParams.append('page', pageIndex);
}
const path = window.location.href.split('?')[0];
const newURL = `${path}?${urlParams}`;
history.pushState({}, '', newURL);
Sources:
MDN - URLSearchParams
MDN - History.pushState()
Get the URL without query string

Replacing iframe google sheet ID with main URL Parameters

I am not sure if this is possible or not... I am trying to replace a specific part of a URL from my iframe with a string that is part of the mainframe's URL parameter.
i.e. I am trying to dynamically replace the iframe google sheets public URL ID to render the sheet associated with the mainframes parameter.
Mainframe URL: www.mysite.com?sfds654fsgfg6sfg54gfhghdf6
iframe src= "https://docs.google.com/spreadsheets/d/e/[google id to insert here dynamically from mainframe]/pubhtml?
Intended Final Result
iframe src= "https://docs.google.com/spreadsheets/d/e/sfds654fsgfg6sfg54gfhghdf6/pubhtml?
javascript is my limitation as well
Thanks,
I'll assume you have the id you want to use as a variable and you also have a place in your page where you want to place this iFrame.
var url_string = window.location.href;
var url = new URL(url_string);
var id= url.searchParams.get("id"); //Or whatever your url parameter is called.
var iFrameDestination = document.getElementbyId("#iframeDest");
var ifrm = document.createElement('iframe');
ifrm.setAttribute('src', 'https://docs.google.com/spreadsheets/d/e/'+id+'/pubhtml');
iFrameDestination.appendChild(ifrm);

how to open url in new window without appending local url

let url = "www.w3schools.com"
{url}
I am trying to open url in the new tab but i am getting http://localhost:9998/www.w3schools.com in the new window instead of https://www.w3schools.com/
let url = "https://www.w3schools.com"
{url}
You need to specify the protocol as well, or the URL will be treated as relative.

Detect media (image, video) type by URL

Based on the URL I need to show either <img> or <video>. Is there a way to detect the media type based on the URL? Or maybe there is some generic html tag that allows to view both image and video? And there is no specific file extension at the end of the URL.
A simple solution in which you extract the extension from the URL and search a Map() to match element type to extension:
const types = new Map([["jpg", "img"], ["gif", "img"], ["mp4", "video"], ["3gp", "video"]])
const url = new URL("http://example.com/image.jpg")
const extension = url.pathname.split(".")[1]
const element = document.createElement(types.get(extension))
element.src = url
Original answer
Make two lists of file extensions that map to img and video files. Store these as two arrays.
When you encounter the URL - user input, JSON from REST, whatever - find the extension in the URL and see which list it belongs to.
Then create your element and inject the URL into its source, such as:
const images = ["jpg", "gif", "png"]
const videos = ["mp4", "3gp", "ogg"]
const url = new URL("http://example.com/image.jpg")
const extension = url.pathname.split(".")[1]
if (images.includes(extension)) {
let img = document.createElement('img');
img.src = url;
} else if (videos.includes(extension)) {
let video = document.createElement('video');
video.src = url;
}
This is not an especially robust solution: perhaps your paths have dots in them, but at least the use of URL() will extract the file portion of a URL that might have parameters.
Note that createElement takes any DOM node as a parent, it doesn't have to be document.
If the URL is pointing to a native file on a remote server, such as a JPG, PNG, or other image (Same for video) than you can to a Split on the last period and grab the extension.
Then once the extension is known, you can perform logic to determine if it's an image extension, or a video extension.
Otherwise, you would just initiate a programmatic download of the file and then perform the same check.

Get url from iframe and update hash in browser url

I've tried a few different things but nothing really worked, basically i need to get the current location/url from the iframe, get the part i want and return it to the hash in the url. how can i do this in javascript?
Select the correct iframe element, pull out the src attribute, do your stuff, assign src to window.location.hash
var iframe = $('iframe');
var src = iframe.attr('src');
window.location.hash = src;
EDIT
If you want to get dynamic location from an iframe you have to access contentWindow property:
var iframe = $('iframe');
var contentWnd = iframe.attr('contentWindow');
var url = contentWnd.window.location.href;
window.location.hash = url;
also interesting reading on getting the contentWindow property:
http://www.bennadel.com/blog/1592-Getting-IFRAME-Window-And-Then-Document-References-With-contentWindow.htm

Categories