I’m trying to change the src attribute of an <iframe> depending if the iframe src has /?foo or not.
I had this solution:
<script>
jQuery(document).ready(function($) {
$('iframe[src*="?foo"]').each(function() {
$('#frame').attr('src', "http://www.example.com/page2");
});
});
</script>
<iframe id="frame" src=„www.example.com/page1/?foo"></iframe>
But my problem is that I have no access to the page, where the iframe is emded so I can't write this code into the <head> of the site.
I have access to both pages www.example.com/page1 and www.example.com/page2
I don’t know how I need to change the code to manipulate the src.. I am not sure if this is even possible, when I have no access to the page with the iframe
As seen in How to retrieve GET parameters from javascript? you can use the following code and call the function parseSecond("foo") to get the foo parameter on page1. You can find more information about this on the question page.
function parseSecond(val) {
var result = "Not found",
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === val) result = decodeURIComponent(tmp[1]);
}
return result;
}
If you then want to redirect to page 2 you can write the following code to redirect the frame from page1 to page2 when the foo parameter has the value equal to bar.
if(parseSecond("foo")=="bar"){
window.location="www.example.com/page2";
}
Related
I have written the JavaScript to modify the DOM attribute based on the click and stored the values in local storage. So after the page loaded, it's getting the value from local storage and set the new attribute to DOM. It's working fine and able to achieve my scenario after perfectly page loaded.
ready(function(){
let element = document.querySelector("body");
if(element.classList.contains("path-api-catalog") ){
let name1 = document.querySelectorAll(".tooltip_heading > h6");
for (let i = 0; i < name1.length; i++) {
let title = name1[i].innerText.replace(/[\n\r]+|[\s]{2,}/g, ' ').trim();
let titleURL = name1[i].parentNode.parentNode.querySelector('.btn.primary-btn').href;
if (localStorage.getItem(title) != null){
if(localStorage[title]===titleURL){
let titleDiv = name1[i].parentNode;
titleDiv.querySelector('.bookmark-icon').setAttribute('onclick','RemoveListItem(event)');
}
}else{
let titleDiv = name1[i].parentNode;
titleDiv.querySelector('.bookmark-icon').setAttribute('onclick','SaveListItem(event)');
}
}
}
})
But I have Ajax category filter to filtering the content. Whenever I click the filter, the content loaded through Ajax. After the Ajax, my JavaScript not modify the attribute and not executed correctly. So, how to execute the JavaScript function even after Ajax content loaded.
I have written the JavaScript to modify the DOM attribute based on the click and stored the values in local storage. So after the page loaded, it's getting the value from local storage and set the new attribute to DOM. It's working fine and able to achieve my scenario after perfectly page loaded.
ready(function(){
let element = document.querySelector("body");
if(element.classList.contains("path-api-catalog") ){
let name1 = document.querySelectorAll(".tooltip_heading > h6");
for (let i = 0; i < name1.length; i++) {
let title = name1[i].innerText.replace(/[\n\r]+|[\s]{2,}/g, ' ').trim();
let titleURL = name1[i].parentNode.parentNode.querySelector('.btn.primary-btn').href;
if (localStorage.getItem(title) != null){
if(localStorage[title]===titleURL){
let titleDiv = name1[i].parentNode;
titleDiv.querySelector('.bookmark-icon').setAttribute('onclick','RemoveListItem(event)');
}
}else{
let titleDiv = name1[i].parentNode;
titleDiv.querySelector('.bookmark-icon').setAttribute('onclick','SaveListItem(event)');
}
}
}
})
But I have Ajax category filter to filtering the content. Whenever I click the filter, the content loaded through Ajax. After the Ajax, my JavaScript not modify the attribute and not executed correctly. So, how to execute the JavaScript function even after Ajax content loaded.
This a basic question (Posting this again, as it was not re-opened after I updated the question). But I couldn't find any duplicates on SO.
This is a script I intend to use in my project on different pages. The purpose is to override the default ID shown in a span element to the order number from the URL parameter session_order. This doesn't affect anything and only enhances the UX for my project.
scripts.js (loaded in the header):
function get_url_parameter(url, parameter) {
var url = new URL(url);
return url.searchParams.get(parameter);
}
And in my HTML template, I call the function this way,
<div onload="this.innerHTML = get_url_parameter(window.location.href, 'session_order');">24</div>
Also tried this,
<div><script type="text/javascript">document.write(get_url_parameter(window.location.href, 'session_order'));</script></div>
When the page is rendered, nothing changes. No errors or warnings in the console either for the first case.
For the second case, console logged an error Uncaught ReferenceError: get_url_parameter is not defined, although script.js loads before the div element (without any errors).
Normally, I'd do this on the server-side with Flask, but I am trying out JavaScript (I am new to JavaScript) as it's merely a UX enhancement.
What am I missing?
Try this:
// This is commented because it can't be tested inside the stackoverflow editor
//const url = window.location.href;
const url = 'https://example.com?session_order=13';
function get_url_parameter(url, parameter) {
const u = new URL(url);
return u.searchParams.get(parameter);
}
window.onload = function() {
const el = document.getElementById('sessionOrder');
const val = get_url_parameter(url, 'session_order');
if (val) {
el.innerHTML = val;
}
}
<span id="sessionOrder">24</span>
Define the function you need for getting the URL param and then on the window load event, get the URL parameter and update the element.
Here you go. Try to stay away from inline scripts using document.write.
function get_url_parameter(url, parameter) {
var url = new URL(url);
return url.searchParams.get(parameter);
}
window.addEventListener('load', function() {
const url = 'https://yourpagesdomain.name/?session_order=hello'; //window.location.href;
const sessionOrder = get_url_parameter(url, 'session_order');
document.getElementById('sessionOrder').innerText = sessionOrder;
});
<div id="sessionOrder"></div>
The order of your markup and script matters...
<div></div>
<script>
function get_url_parameter(url, parameter) {
var url = new URL(url);
return url.searchParams.get(parameter);
}
</script>
<script>
document.querySelector('div').innerHTML = get_url_parameter('https://example.com?session_order=2', 'session_order');
</script>
I need some simple code on pure JavaScript (NOT jQuery!) that will add certain end to all the internal links on a page (i.e. to all the links that contain website domain in its href attribute), something like:
var pagelinks = document.getElementsByTagName('a');
for(var i in pagelinks) {
if(pagelinks.getAttribute('href').indexOf(document.domain) != -1) {
pagelinks[i].setAttribute('href',currenthref+'my_end');
}
}
!!! NOTE: it's not working script — it's only "something like" what I need
For example the internal links on a page are:
Showcase
Contacts
...
I need
Showcase
Contacts
...
If I understand your question correct this is what you want:
var domain = 'www.youtube.com';
var pagelinks = document.getElementsByTagName('a');
for (var i = 0; i < pagelinks.length; i++) {
var current = pagelinks[i].getAttribute('href');
if (current.indexOf(domain) !== -1) {
pagelinks[i].setAttribute('href', current + '?my_end');
}
}
Updated fiddle: https://jsfiddle.net/cm69qmnL/6/
You have to specify the domain you want to check the href attributes against and then run a loop which checks each anchor's href attribute, checks it against the specified domain and updated the href if the domain exists in current.
Because of the widget format I'm working with I have a page which has multiple iframes embedded within iframes. I won't paste the code as it's vast and unwieldy but it is essentially just this:
<html>
<head></head>
<body>
<iframe>
<html>
<head></head>
<body>
<iframe>
<html>
<head></head>
<body>
<iframe>
<html>
<head></head>
<body>
blah
</body>
</html>
</iframe>
</body>
</html>
</iframe>
</body>
</html>
</iframe>
</body>
</html>
However, there may be more - or less - iframes dependent upon the page and template I use.
I'm trying to therefore get the ID of all of the iframes in this page, from within the most-embedded iframe.
Is this possible with jQuery? I've tried a few snippets of code but had no luck:
$('iframe', window.parent.document).each(function() {
console.log($(this).attr("id"));
});
$('iframe', parent.document).each(function() {
console.log($(this).attr("id"));
});
$('iframe').each(function() {
console.log($(this).attr("id"));
});
The output of these is a single ID string - and unfortunately it's not the iframe I'm looking to control.
Thanks in advance,
EDITED
This returns an iframe element which has the wanted id, and null, if the wanted id is not found.
function searchIds(wantedId) {
var idArray = [], n,
search = function (iframes) {
var n;
for (n = 0; n < iframes.length; n++) {
if (iframes[n].frames.length > 0) {
search(iframes[n].frames);
}
idArray.push(iframes[n].frameElement.id);
idArray.push(iframes[n].frameElement);
}
};
search(window.top.frames);
for (n = 0; n < idArray.length; n += 2) {
if (idArray[n] === wantedId) {
return idArray[n + 1];
}
}
return null;
}
Notice, that searchIds() can't be run before onload of the main window has been fired.
I do not believe you can reference the iframe's children directly. You will need to recursively search each iframe using it's .contents() call.
As far as I know, this will only work as long as the same-origin policy is not violated (i.e. the iframes must point to the same domain).
From the most embedded iframe:
var ids = (function up( context, ids ){
ids = ids || [];
// proceed if we're not at the top window yet
if( context !== window.top){
// point context to parent window (or top if no parent).
context = context.parent || window.top;
// get the id of the first iframe in parent window;
// this will break if there are sibling iframes
ids.push(context.document.getElementsByTagName('iframe')[0].id);
// recursive call to traverse parents
return up(context, ids);
} else {
// otherwise return the list of ids
return ids;
}
}(this)); // 'this' is the initial context - current window
console.log( ids );