Get and print hash in iframe - javascript

I Want to get hash from this url
http://www.mywebsite.com/#/aaaaaaaa
aaaaaaaa
And add to iframe :
<iframe src="http://www.example.com/url/aaaaaaaa" frameborder="0">
Javascript code :
<script>
var hhash = window.location.hash.substr(1);
alert(hhash);
</script>

You can also use the lastIndexOf() function to locate the last occurrence of the / character in your URL, then the substr() function to return the substring starting from that location:
var hhash =(window.location.href.substr(window.location.href.lastIndexOf('/') + 1));
document.write("<iframe src=\"example.com/url/\""+hhash+"frameborder=\"0\">");

Your title and question is a little bit misleading.
If you just want to print the hash tag, you can create an element and set the innerText to your hash, like so:
// Use hash instead of href here! :) This is just to make the example work
const lastPart = window.location.href.split( '/' ).pop();
document.querySelector( '.hash' ).innerText = lastPart;
<div class="hash"></div>
If you want to alter the src of the iFrame, you could use the first example combined with setAttribute.
// Use hash instead of href here! :) This is just to make the example work
const lastPart = window.location.href.split( '/' ).pop();
const src = 'http://example.org/url/' + lastPart;
document.querySelector( '.hash' ).setAttribute( 'src', src );
document.querySelector( '.url' ).innerText = 'iframe points to ' + src;
<iframe class="hash"></iframe>
<div class="url"></div>

You can get hash part (without #/) with:
var hash = window.location.hash.replace('#/', '');
Then you get the current iframe src attribute with :
var src = document.getElementsById('YourIframeId').getAttribute('src');
And now you update the iframe src:
document.getElementsById('YourIframeId').setAttribute('src',src + '/' + hash);

Related

How to get the wildcard in the URL and apply argument to a link

Hello I am super new to building websites. Please excuse my lacking terminology!!
I have a website that has Wildcard sub-domains. It is using this script to pull the wildcard sub-domains usernames.
<p id="dist-info"></p>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
return;
var get_data_url = 'https://backoffice.WEBSITE.com/api/v2/public/users/{username}';
$.getJSON(get_data_url, function( data ) {
var dist_info = "<p>"+data.response['first-name']+"</p>" +
"<p>"+data.response['last-name']+"</p>" +
"<p>"+data.response['distributor-id']+" "+data.response.email+"</p>" +
"<p>"+data.response['image-url']+"</p>" +
"<p>Phone: "+data.response.phone+"</p>";
$('#dist-info').html(dist_info);
});
});
</script>
Now I need to make a URL that will parse the username/user id out of the Wildcard Subdomain page. What code do I need to use?
For example
The URL is
USERNAME.WEBSITE.com/page/subpage/
I need to make this URL
backoffice.WEBSITE.com/page?sponsor-id=USERNAME
What do I need to do so that the username from the first page is parsed out and applied to the link of the second URL
You want to modify this JavaScript so it uses the subdomain instead of {username}?
$(document).ready(function() {
var get_data_url = 'https://backoffice.WEBSITE.com/api/v2/public/users/';
var hostname_parts = location.hostname.split('.');
var username = hostname_parts.shift();
// add username to the data URL
get_data_url += username;
// add username to some link on the website
var $aTag = $('#id-of-the-link');
var link_url = $aTag.attr('href');
link_url += username;
// set the new href attribute
$aTag.attr('href', link_url);
location.hostname gives you USERNAME.WEBSITE.com, split() splits it into parts separated by a dot. shift() takes the 1st element of this array (you could also use hostname_parts[0]) and with += you concatenate it to the URL.
The second example shows how to add the username at the end of a link like
click
Edit: added example for changing a href attribute

Add a part of URL in Iframe with javascript

i want to add last part of url in iframe
suppose my url is http://myweb.com/123456/
i want to add 123456 in iframe like
<iframe src ="http://myweb.com/demo.html?user=123456"></iframe>
Please Help, Thanks in advance
Here the solution. Purely using JavaScript no jQuery.
Steps:
Extract url's last part.
Get the iframe element using it's id
Get the current value of src attribute of iframe
Append the concatenate the extracted last part of url to current value of src
Update the attribute value
var url = "http://example.com/12345";
var lastPart = url.split('/').pop();
console.log("Last part of url: " + lastPart);
var myIframe = document.getElementById('myIframe');
var iframeSrc = myIframe.getAttribute("src");
console.log("Initial src value: " + myIframe.getAttribute("src"));
myIframe.setAttribute("src", iframeSrc + lastPart);
console.log("src after appending: " + myIframe.getAttribute("src"));
<iframe id="myIframe" src ="https://example.com?user="></iframe>
You can just the following to add any values you may need to the end of the src (Note this is jQuery, so this may not be what you are interested in):
var value = "123456";
$('iframe').attr('src', $('iframe').attr('src') + value);
document.write("New URL: " + $('iframe').attr('src'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<iframe src ="http://myweb.com/demo.html?user="></iframe>

jquery find specific word on src and remove it

I need to find this word 500x462 in a src image att and remove it . Right now the image ends with 500x462 + jpg and i want it to end with image name + jpg
I forgot to say that the website is a wordpress theme generated by php so i need the script to run after the php
Heres a example of the code i want to change
Using a regex:
$("img").each(function(){
$(this).attr('src', $(this).attr("src").replace(/[\d]{3}x[\d]{3}/, ''));
});
This will remove any sequence of [3 digits][the letter x][3 digits] in all images src attribute.
Use the jquery and .replace(), so for example:
HTML:
<img src="http://www.placehold.it/500x462.jpg">
JQuery:
var string = $("img").attr("src");
var new_string = string.replace('500x462', '');
alert(new_string);
Working DEMO.
Assuming that the image src always ends with a file extension.
<img src="ABC500x462blah500x462.jpg">
<script>
var src = $('img').attr('src');
var textToCheck = '500x462';
$('img').attr('src', src.split('.')[0].replace(new RegExp(textToCheck +"$"),"") // check for the text occurring at the end
+ "." + src.split('.')[1]);
alert($('img').attr('src'));
</script>
Example : https://jsfiddle.net/mu2d6qr7/
I wrote a quick jQuery function to do this for you. First parameter is a jQuery selector and second parameter is the string you would like to remove.
window.srcRemoveString = function(selector, string) {
$(selector).each(function(){
var src = $(this).attr('src');
var filename = src.split('/');
filename = filename[filename.length - 1];
var newFilename = filename.replace(string, '');
$(this).attr('src', src.replace(filename, newFilename));
});
}
srcRemoveString('img', '500x462');
Best way to split text in image source
jQuery(".size-post-thumbnail").each(function(){
let src = jQuery(this).attr("src").split("-220x146");
src = src[0]+src[1];
jQuery(this).attr("src", src);
jQuery(this).removeAttr('srcset');
});

Adding javascript variable to hyperlink within script

I have been trying to create a hyperlink using a variable defined earlier in the same function to append:
var NAMEVARIABLE = responseArray[i].Name;
var TITLE_Game = document.createElement("p");
TITLE_Game.className = "TITLE_Game";
TITLE_Game.innerHTML = "<a href='Game_NAMEVARIABLE.html'>Games</a>";
I have tried the following using the solution found here: Passing Javascript variable to <a href >
Games
But that didn't work. I then tried adding an ID:
<a id="link" href="Game_.html?propid=">Games</a>
And adding this to the script: document.links["link"].href += NAMEVARIABLE;
This didn't work either. These links are occuring within Isotope, which I've run into newbie-problems making sure my JSON data is loading before the script executes. That's all working now, but I'm not sure if the reason the above methods aren't working is because of a similar issue, or if they simply are not the proper way to go about this.
Any help is much appreciated. Thank you
first of all, try debug your variable :
var NAMEVARIABLE = responseArray[i].Name;
alert(NAMEVARIABLE);
is it returning the desired return value or not.
and then the second thing, in your first style of script, try this instead :
TITLE_Game.innerHTML = "<a href='Game_"+NAMEVARIABLE+".html'>Games</a>";
I assumed you have (static) html collection with game_[number_id].html format
and if it's so, you can try further with your second style of script, and change it to this :
Games
you need to learn further about javascript strings concatenation
Use string concatenation to build up your inner html string.
Example:
var nameVariable = 'Foo';
var innerHtmlText = nameVariable + 'bar';
$('#someElement').html(innerHtmlText);
The contents of someElement will then contain the text: 'Foobar';
You just need string concatenation. modify link's href onclick would be considered as spam in most modern browser.
<div id="result">
the result:
</div>
<script type="text/javascript">
var name = "foo_bar";
var url = "page.html?key=" + name; //or.. "page_" + name + ".html";
var link = 'link here';
$("#result").addClass("g_title");
$("#result").append(link);
</script>
This can be achieved by either (i.e. pure JS or jQuery) ways without much hassle. Suppose you have this <a> element with some href
<a id="Link" href="/collection/categories/">Games</a>
Pure JavaScript way:
window.onload = function() {
var link= document.getElementById('Link'),
url = link.href + responseArray[i].Name + '.html';
link.setAttribute('href', url);
}
Using Jquery:
$(function(){
var link= $('#Link'),
url = link.attr('href') + responseArray[i].Name + '.html';
link.attr('href', url);
});

Capture incoming URL Parameters, then pass to iFrame Src with Javascript

So trying to figure out how to do this with window.location in Javascript. I'm sending users to our site with an appended URL with a Google Analytics code that I need to pass to an iframe src on that page. I'd assume Javascript could do this (note - I cannot use PHP)...
This is what I want to do:
I'd send users to the page with all the campaign data in tact. For example a user would click on this link:
http://www.xyz.com/index.html?utm_source=Facebook&utm_campaign=Facebook+May&utm_medium=click
They would be directed to that page, that then has this iFrame on it. The code on the store side would need to pick up utm_source, utm_campaign, utm_medium and include these parts in the IFRAME SRC So this bit:
<iframe height="960px" frameborder="0" scrolling="no" width="958px" src="http://www.abc.com/minis"></iframe>
now becomes:
<iframe height="960px" frameborder="0" scrolling="no" width="958px" src="http://www.abc.com/minis?utm_source=Facebook&utm_campaign=Facebook+May&utm_medium=click"></iframe>
Any javascript suggestions would be greatly appreciated. Note - I cannot use PHP.
UPDATE:
Got this to work!! Yay, but now I need to edit it a bit:
So say the appended url that was clciked was this:
http://abc.com/index.html?apple&orange&peach
and I need the iframe src to be this
http://xyz.com/minis?orange&peach
I moved a few things around in the script, but is now only grabbing orange and not the other & attribute (peach). please advise if there is a better way to work (without have all the params and then depending on what link comes in, some of the & will be undefined:
<body>
<script type="text/javascript">
$(function() {
var loc = window.location.toString(),
params = loc.split('&')[1],
params2 = loc.split('&')[2],
params3 = loc.split('&')[3],
params4 = loc.split('&')[4],
params5 = loc.split('&')[5],
params6 = loc.split('&')[6],
iframe = document.getElementById('myIframe');
alert(iframe.src);
iframe.src = iframe.src + '?' + params + '&' + params2 + '&' + params3 + '&' + params4+ '&' + params5;
alert(iframe.src);
});
</script>
<iframe id="myIframe" src="http://www.xyz.com/minis"></iframe>
</body>
This little snippet should do, here all you have to do is grab the bit after ? as a string and append it to the iframe source.
var loc = window.location.toString(),
params = loc.split('?')[1],
iframe = document.getElementById('myIframe');
iframe.src = iframe.src + '?' + params;​​​​​​​​​​​​​​​​
Just use window.location.search.
const iframe = document.getElementById('frame');
iframe.src = iframe.src + window.location.search;​​​​​​​​​​​​​​​​

Categories

Resources