Basics – Optional
What is iFrame ? An iFrame is a HTML element that allows to embed an external web page into your HTML page using src attribute (src stands for source).
What is a URL Parameter ?
Parameters are used in the url to pass extra information to the server, that may be used by the server to send a customised response back to the browser or use it otherwise.
A parameter has a key and a value. Example: client=firefox
here client is the key of the parameter and firefox is the value
What is a Query String ?
Query String is string included in the url after a question mark (?)
A Query String is the string passed to the url in the form of parameters, it can contain one or more parameters, each parameter is separated using the ampersand (&)
Below is a real world use-case of query string and parameters.
Explanation – Lets look at the Query string breakdown
In the above example, we search for a keyword “mrvirk” in Google search, and the page passes 3 parameters back to the Google server that helps G Search to provide you results for the keyword.
- Parameter 1 (client=firefox-b-d): tells google what browser user is on, in my case its Firefox
- Parameter 2 (channel=trow): tells google the channel
- Parameter 3 (q=mrvirk): tells google what the user searched for, in this case mrvirk
Now, the basics are covered lets look at the solution to passing parameters to the iframe url.
Step 1: Create an Iframe element, with an id
<iframe id="myIframe" frameborder="0" marginwidth="0" marginheight="0" scrolling="NO" width="100%" height="100%"></iframe>
<script> let myIframe = document.getElementById("myIframe"); let url_string = "https://ads.mrvirk.com/"; let width = "728"; let height = "90"; let geo = "uk"; let adsURL = url_string+"?geo="+geo+"&size="+width+"x"+height; console.log(adsURL); myIframe.src = adsURL; </script>
In the code, firstly we identify our iframe element by id and assign it to a variable called myIframe, this later helps us to work with the iframe with ease.
Then, we need to construct the url using our parameter values that are size (width x height) and geo in this example.
Finally assign, the url to iframe object using the src property of iframe.
Here you can get the full code on Github
This article also provide solution to – How to pass query string in iframe src ?