Grab URL parameter passed and add to iframe URL - javascript

I'm using typform embed code but they didn't provide any sample code to grab a custom parameter from the URL and insert it into the embed code they generate. They explain it can be done though. The steps are outlined below. I'm looking for some code that will grab any parameters passed on the URL and add them to the typeform URL within the iframe. Hopefully, the timing works out and by the time the iframe code executes, it will have the parameter passed.
User clicks on link https://mysite/embedpage.html?sfid=2324234
Page code should read the sfid passed to the URL and add this parameter plus the value passed to the typeform URL within the embed code as seen below:
<html>
<head>
</head>
<body>
<iframe id="typeform-full" width="100%" height="100%" frameborder="0"
src="https://mysite.typeform.com/to/tpEHHt?sfid=2324234">
</iframe>
<script
type="text/javascript" src="https://embed.typeform.com/embed.js">
</script>
</body>
</html>

Did you try something like this ?
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
document.getElementById('typeform-full').src = `https://mysite.typeform.com/to/tpEHHt?sfid=${getQueryVariable('sfid')}`;

I believe this question has been asked before on Stackoverflow.
I made a working example on glitch that you can copy and use for your own.
Similar to #Twisting nether solution, extract the query parameter from the current page, with a function, and pass it to Typeform Embed SDK.
Hope it helps :)

Related

Sanitizing parameters passed from url to iframe src attribute

On domain-one.com an iframe elements get written through javascript with the code below.
The src attribute url of that iframe needs to receive the url parameters that are given to domain-one.com
e.g.
domain-one.com?par1=value1&par2=value2
<script type="text/javascript">
var params = window.location.search.substring(1);
if (params && params.length > 0) {
document.write('<iframe src="https://example.com/page?col=2&' + params + '"></iframe>');
}
else {
document.write('<iframe src="https://example.com/page"></iframe>');
}
</script>
With this code any number of params and any value can be given to domain-one.com.
This feels rather unsecure.
What is best practice to minimize the risks? Does this needs escaping or encoding?
What vulnerability can be executed client side by using the code above.
Thanks in advance

How to shorten url when sharing a webpage from my website on social media?

How to shorten url when sharing a webpage from my website on social media?
I hope it can be done with javascript and apis, I've checked the bitly api, but don't know how to get starting.
Thanks.
I have 2 useful resources for you:
This one for google url shortener: http://www.i-visionblog.com/2014/07/google-url-shortener-api-javascript.html
And this one for bit.ly: https://bdhacker.wordpress.com/2010/03/30/dynamically-use-bitly-in-your-site-easiest-way/
First, you need an account on http://bit.ly. To create one, go to the
site and register.
Once you’ve registered, login and go to your Account page. There, you
will find your API key.
Put this in your HTML HEAD:
<script type="text/javascript" charset="utf-8" src="http://bit . ly/javascript-api.js?version=latest&login=******&apiKey=*****************"></script>
(remove spaces in bit.ly url. stackoverflow doesn't allow to post answers with that url)
Put this before </body>:
<script>
// Bit.ly API
BitlyCB.shortenResponse = function(data) {
var sss = '';
var first_result;
// Results are keyed by longUrl, so we need to grab the first one.
for (var r in data.results) {
first_result = data.results[r]; break;
}
sss = first_result["shortUrl"].toString();
document.getElementById("qlink").value = sss;
}
BitlyClient.shorten(window.location, 'BitlyCB.shortenResponse');
</script>
And this, somewhere in your page:
<h3>Link to this page</h3><br>
Use this link to tell others about this page! <input onclick = "this.select()" type = 'text' id = "qlink" style = "width:100%;">

Display part of URL on a page (i.e. Instagram Access Token)?

What I'm trying to achieve is when a user authenticates with Instagram, and they're redirected to a page like "http://domainnamehere./instagram#access_token=27744335.fcaef44.a95s9e741f3c4ea7bcad21d80809ca40"
To be able to print the "27744335.fcaef44.a95s9e741f3c4ea7bcad21d80809ca40" string on a part of the web page, i.e.
<p>Here is your access token: ________</p>
I know how to print the whole URL using javascript, using this:
<h3 id="right">
<script type="text/javascript">
document.write(location.href);
</script>
</h3>
But how can I set it up to get only part of the URL?
Exactly what I'm trying to achieve can be seen here live http://theultralinx.com/instagram (click "setup instagram," authenticate, and then the next page shows the access token.
Thank you!
You can still look for an URI parser, but it might be obtained using basic string functions like indexOf and substring as follows:
var uri = "http://domainnamehere./instagram#access_token=27744335.fcaef44.a95s9e741f3c4ea7bcad21d80809ca40";
var indexOfHashVar = uri.indexOf("access_token=");
// 13 is the number of characters of "access_token="
var token = uri.substring(indexOfHashVar + 13);
console.log(token);
As #PhistucK suggested in some comment, you might get the hash part of the whole uri using window.location.hash, thus my sample may be altered in the first line with:
var uri = window.location.hash;
Never use document.write, it is discouraged.
This should work.
HTML -
<p>Here is your access token: <span id="access-token"></span></p>
JavaScript -
window.addEventListener("load", function () {
// Getting the part of the URL that starts with #.
var hash = document.location.hash,
// Storing the string for which we search in the hash.
accessTokenParameter = "access_token=";
// Setting the found value as the content of the access-token element we created
// above by taking the part of the hash (substring) that begins after the
// parameter by getting the index of the character (indexOf) with which the
// parameter name starts and adding the length of the parameter name (and =)
// in order to get past the name and start from the value.
document.getElementById("access-token").innerHTML =
hash.substring(hash.indexOf(accessTokenParameter) +
accessTokenParameter.length);
}, false);
In order to support Internet Explorer as well, you can use window.onload = or name the function and use window.attachEvent after feature detecting it.
<h3 id="right">
<script type="text/javascript">document.write(window.location.hash.split("access_token=")[1]); </script>
</h3>
you can use this
<h3 id="right"> <script type="text/javascript"> var href = location.href; href = href.replace("http://domainnamehere./instagram#access_token=",""); document.write(href); </script> </h3>
if ur link is always like the link in the question (same domain & no other variables) u can use this:
var url =location.href ;
var res = url.slice(45);
console.log(res);

get javascript url parameter from script source file in HTML

My HTML block as follows,
<html>
<title>Example</title>
<head>
</head>
<body>
<h2>Profile Photo</h2>
<div id="photo-container">Photo will load here</div>
<script type='text/javascript' src='http://example.com/js/coverphoto.js?name=johndoe'></script>
</body>
</html>
and I have saved this file as test.html. In JavaScript source the name will be dynamic.
I want to collect the name in coverphoto.js. Tried in coverphoto.js as,
window.location.href.slice(window.location.href.indexOf('?') + 1).split('&')
but it is getting the html file name (test.html) only. How can I retrieve the name key from http://example.com/js/coverphoto.js?name=johndoe in coverphoto.js?
To get the URL of the current JavaScript file you can use the fact that it will be the last <script> element currently on the page.
var scripts = document.getElementsByTagName('script');
var script = scripts[scripts.length - 1];
var scriptURL = script.src;
Please note that this code will only work if it executes directly within the JS file, i.e. not inside a document-ready callback or anything else that's called asynchronously. Then you can use any "get querystring parameter" JS (but make sure to replace any location.search references in there) to extract the argument.
I'd suggest you to put the value in a data-name argument though - that way you can simply use e.g. script.getAttribute('data-name') to get the value.
You can use the stack trace technique.
This technique will detect the source of the JS file the script is running from and it doesn't depend on the way you have injected the script. It can be dynamically injected (ajax) or in whatever method you can think of.
Just use the following code in your JS file:
const STACK_TRACE_SPLIT_PATTERN = /(?:Error)?\n(?:\s*at\s+)?/;
const STACK_TRACE_ROW_PATTERN1 = /^.+?\s\((.+?):\d+:\d+\)$/;
const STACK_TRACE_ROW_PATTERN2 = /^(?:.*?#)?(.*?):\d+(?::\d+)?$/;
const getFileParams = () => {
const stack = new Error().stack;
const row = stack.split(STACK_TRACE_SPLIT_PATTERN, 2)[1];
const [, url] = row.match(STACK_TRACE_ROW_PATTERN1) || row.match(STACK_TRACE_ROW_PATTERN2) || [];
if (!url) {
console.warn("Something went wrong. This probably means that the browser you are using is non-modern. You should debug it!");
return;
}
try {
const urlObj = new URL(url);
return urlObj.searchParams;
} catch (e) {
console.warn(`The URL '${url}' is not valid.`);
}
};
const params = getFileParams();
if ( params ) {
console.log(params.get('name'));
}
Note:
The params.searchParams will not work for IE browser, instead you can use params.search. But, for the sake of you nerves don't. Whoever is still using IE in 2020, just let him suffer.

How to get the currently loading script name and the url variable of the script?

I am loading a script using the script embed tag and I want to get the url variables and the loading script name inside the script. Is it possible? For Example,
<script src="test.js?id=12"></script>
Inside test.js is there any way to get the url variable id?
Any help would be appreciated.
Thanks,
Karthik
Aside from the answers in the linked post, FWIW with Firefox 4 only you can (with caveats); document.currentScript.src which will return the full url, including arguments.
Thanks for all your efforts I have made that working by assigning an id attribute in the script tag and accessed via jQuery,
<script src="test.js?id=12" id="myScript"></script>
var currentScript = $("#myScript").attr('src'); //This will give me my script src
Thanks,
Karthik
If you want to get a variable from the current URL you can use this:
function queryParser(url){
this.get=function(p){return this.q[p];}
this.q={};
this.map=function(url){
url=url || window.location.search.substring(1);
var url=url.split('&');
var part;
for(var i=0;i<url.length;i++){
part=url[i].split('=');
this.q[part[0]]=part[1];
}
}
this.map(url);
}
var query=new queryParser();
// assuming you have ?test=something
alert(query.get('test'));
I recommend you map the result, so you don't re-parse whenever you want to find a specific element.
I don't really know why you'd pass a query string in a script tag like that, unless you specifically want off-site includes with a simple robust system for various effects. Or are actually using PHP to handle that request.
If you want to "send" a variable to one of your scripts, you can always do:
<script type="text/javascript">
var myVar="I'm in global scope, all scripts can access me";
</script>
<script src="test.js?id=12"></script>
If you really need to get the URL of the currently included script, you can use the code supplied by my peers in the other answers, you can then use:
var query=new queryParser(scriptURL);
alert(query.get('id'));// would alert 12 in your case
Navigating through the link on your comments you can get the proper answer.
Anyway, to make things easier:
var allScripts=document.getElementsByTagName('script');
var indexLastScript= allScripts.length -1;
alert (allScripts[indexLastScript].src);
This will show up "test.js?id=12" as a regular String so its up to you to split it in order to get de param.
Hope it helps, I've tried it on the run over the Chrome Javascript Console. :D.

Categories

Resources