Get Elements inside iframe which is nested inside Frame in javascript? - javascript

Edit:I'have solved the problem. You can check my comment below.
I want to get html elements of all iframes.
These iframes can be located in my main page or they can be nested iframes.
I want to get all iframes elements.
There are many example on the internet to get elements of a specific iframe by id.
For example;
Get element value inside iframe which is nested inside Frame in javascript?
But i dont want to specify main iframe id or anything like this. I want to reach all iframes.(nested or not nested)
I am very pleased if you can help me.
Thank you.
I also have an example but it can reach only top iframe on the page with specific id.
Here is my example;
var htmlDocument = document_root;
var numberOfFrame = $("iframe[id^='" + rules.frameId + "']").length;
if (numberOfFrame > 0) {
htmlDocument = $("iframe[id^='" + rules.frameId + "']")[numberOfFrame - 1].contentDocument;
formName = $("iframe[id^='" + rules.frameId + "']")[numberOfFrame - 1].id;
var iframeList = [];
iframeHTMLObjectList.push(htmlDocument);
for (i = 0; i < htmlDocument.getElementsByTagName("iframe").length; i++) {
iframeList.push(htmlDocument.getElementsByTagName("iframe")[i]);
}
for (i = 0; i < iframeList.length; i++) {
iframeHTMLObjectList.push(iframeList[i].contentWindow.document);
}
console.log(formName);
}

I've solved the problem with recursive method.
Here is my method:
function getIframeElements(htmlDocument) {
var frames = htmlDocument.getElementsByTagName("iframe");
if (frames.length > 0) {
for (var i = 0; i < frames.length; i++) {
try {
formName = frames[i].id;
getIframeElements(frames[i].contentWindow.document);
} catch (err) {
console.log(err);
}
}
}
if (!iFrameArr.includes(htmlDocument)) {
iFrameArr.push(htmlDocument);
}
return iFrameArr;
}

Related

Javascript pulling content from commented html

Bit of a JS newbie, I have a tracking script that reads the meta data of the page and places the right scripts on that page using this:
var element = document.querySelector('meta[name="tracking-title"]');
var content = element && element.getAttribute("content");
console.log(content)
This obviously posts the correct tag to console so I can make sure it's working .. and it does in a test situation. However, on the actual website the meta data i'm targeting is produced on the page by a Java application and beyond my control, the problem is it is in a commented out area. This script cannot read within a commented out area. ie
<!-- your tracking meta is here
<meta name="tracking-title" content="this-is-the-first-page">
Tracking finished -->
Any ideas appreciated.
You can use this code:
var html = document.querySelector('html');
var content;
function traverse(node) {
if (node.nodeType == 8) { // comment
var text = node.textContent.replace(/<!--|-->/g, '');
var frag = document.createDocumentFragment();
var div = document.createElement('div');
frag.appendChild(div);
div.innerHTML = text;
var element = div.querySelector('meta[name="tracking-title"]');
if (element) {
content = element.getAttribute("content");
}
}
var children = node.childNodes;
if (children.length) {
for (var i = 0; i < children.length; i++) {
traverse(children[i]);
}
}
}
traverse(html);
One way is to use a NodeIterator and get comment nodes. Quick example below. You will still need to parse the returned value for the data you want but I am sure you can extend this here to do what you want.
Fiddle: http://jsfiddle.net/AtheistP3ace/gfu791c5/
var commentedOutHTml = [];
var iterator = document.createNodeIterator(document.body, NodeFilter.SHOW_COMMENT, NodeFilter.FILTER_ACCEPT, false);
var currentNode;
while (currentNode = iterator.nextNode()) {
commentedOutHTml.push(currentNode.nodeValue);
}
alert(commentedOutHTml.toString());
You can try this. This will require you to use jQuery however.
$(function() {
$("*").contents().filter(function(){
return this.nodeType == 8;
}).each(function(i, e){
alert(e.nodeValue);
});
});

jQuery: Storing a Div name in a variable, then calling it in an action

So i've been trying to wrap my head around this, all i'm trying to do is store a div name in a variable for easy editing, then allow it to be called in standard actions such as show/hide.
Without the variables, my code works fine but with them it will not load the div, i've done a console log to make sure it knows what the div name is based off the stored variable and it returns correctly.
Here is my code:-
var buttonActive = 0;
var yourMenuDiv = '.menu-menu-1-container';
$(function() {
$(yourMenuDiv).before('<div class="responsiveButton"><div id="rBBar"></div><div id="rBBar"></div><div id="rBBar"></div></div>');
$(yourMenuDiv).before('<div class="responsiveMenu"><div id="responsiveTitle"></div></div>');
$(yourMenuDiv + 'ul').clone().appendTo('.responsiveMenu');
$('.home #logoImage').clone().appendTo('#responsiveTitle');
console.log(yourMenuDiv);
$(window).resize(function() {
if ($(window).width() < 600) {
$(yourMenuDiv).hide();
$('.responsiveMenu, .responsiveButton').show();
}else{
$('.responsiveMenu').removeClass('expandMenu');
$('.responsiveButton').removeClass('expandMenuButton');
$('.responsiveMenu, .responsiveButton').hide();
$(yourMenuDiv).show();
buttonActive = 0;
}
});
$(function() {
if ($(window).width() < 600) {
$(yourMenuDiv).hide();
$('.responsiveMenu, .responsiveButton').show();
}else{
$('.responsiveMenu, .responsiveButton').hide();
$(yourMenuDiv).show();
buttonActive = 0;
}
});
$('.responsiveButton').click(function() {
if (buttonActive == 0){
$('.responsiveMenu').addClass('expandMenu');
$('.responsiveButton').addClass('expandMenuButton');
buttonActive = 1;
}else{
$('.responsiveMenu').removeClass('expandMenu');
$('.responsiveButton').removeClass('expandMenuButton');
buttonActive = 0;
}
});
});
Thank you
You should try something like:
var yourMenuDiv = $('.menu-menu-1-container');
and then just call the methods with: yourMenuDiv.methodHere.
In your code:
$(yourMenuDiv + 'ul').clone().appendTo('.responsiveMenu');
Does the above line work correctly? - I mean should there be a space character in between. Something like below:
$(yourMenuDiv + ' ul').clone().appendTo('.responsiveMenu');
and as a matter of interest. Does it make any difference if you place your first two lines of code:
var buttonActive = 0;
var yourMenuDiv = '.menu-menu-1-container';
after $(function() { ?

Stop javascript redirection on href="javascript:void"

I've been using a script which prefixes redirect.php on "onmouseevent" triggers. But I don't want it on certain sites, like google etc. Please see the code below:
var matchavailable = 0;
var disallowinks = "google,microsoft,yahoo";
$n("a").mousedown(function () {
var linkArray = disallowlinks.split(',');
for (var i = 0; i < linkArray.length; i++) {
if ($n(this).attr('href').indexOf(linkArray[i]) > 0) {
matchavailable = 1;
break;
}
else {
matchavailable = 0;
}
}
if (matchavailable == 0) {
if ($n(this).hasClass('linked')) {
}
else
{
$n(this).attr('href', "http://yoursite.com/redirect.php?q=" + encodeURIComponent($n(this).attr('href')));
$n(this).attr('target', '_blank');
$n(this).addClass("linked");
}
}
});
The javascript runs so far so good on all anchor tags. Just that, I have a popup which I show on my website and when I try to close the popup (X marks the spot), the redirect.php gets prefixed on that as well.
So my question is, how do we disallow the script to NOT run on anchor tags with the value starting with "javascript" ?
For example, i don't want it to run on:
<a href="javascript:void"> or <a href="any random parameter">
How do I go about this? WOuld be great to get some help

Greasemonkey - Find link and add another link

We have an internal inventory at work that is web based. I am looking at add a link say under a link on the page. There is no ID, or classes for me to hook into. Each link at least that I want to add something below it, starts with NFD. I basically need to pull the link text (not the link itself the text that appears to the end user) and use that in my url to call a web address for remoting in.
var links = document.evaluate("//a[contains(#href, 'NFD')]", document, null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i=0; i < links.snapshotLength; i++)
{
var thisLink = links.snapshotItem(i);
newElement = document.createElement("p");
newElement = innerHTML = ' Remote';
thisLink.parentNode.insertBefore(newElement, thisLink.nextSibling);
//thisLink.href += 'test.html';
}
Edit:
What I am looking for basically is I have a link NFDM0026 I am looking to add a link now below that using the text inside of the wickets so I want the NFDM0026 to make a custom link to call url using that. Like say a vnc viewer. The NFDM0026 changes of course to different names.
Here's how to do what you want (without jQuery; consider adding that wonderful library):
//--- Note that content search is case-sensitive.
var links = document.querySelectorAll ("a[href*='NFD']");
for (var J = links.length-1; J >= 0; --J) {
var thisLink = links[J];
var newElement = document.createElement ("p");
var newURL = thisLink.textContent.trim ();
newURL = 'http://YOUR_SITE/YOUR_URL/foo.asp?bar=' + newURL;
newElement.innerHTML = ' Remote';
InsertNodeAfter (newElement, thisLink);
}
function InsertNodeAfter (newElement, targetElement) {
var parent = targetElement.parentNode;
if (parent.lastChild == targetElement)
parent.appendChild (newElement);
else
parent.insertBefore (newElement, targetElement.nextSibling);
}

Find an anchor in a Div with javascript

In javascript I have a reference to a div. In that div is an anchor element with a name='foundItem'
How do I get a reference to the anchor with the name foundItem which is in the Div I have the reference of?
There are 'many' foundItem anchors in other divs on the page. I need 'this' DIVs one.
// assuming you're not using jquery or mootools
// assume div is mydiv
var lst = mydiv.getElementsByTagName('a');
var myanchor;
for(var i=0; i<lst.length; ++i) {
if(lst[i].name && lst[i].name == 'foundItem') {
myanchor = lst[i];
break;
}
}
// the mootools method
var myanchor = $(mydiv).getElement('a[name=foundItem]');
You can use the getElementsByTagName method to get the anchor elements in the div, then look for the one with the correct name attribute:
var found = null;
var e = divReference.getElementsByTagName('A');
for (var i=0; i < e.length; i++) {
if (e[i].name && e[i].name == 'foundItem') {
found = e[i];
break;
}
}
If found is not null, you got the element.
If you happen to use the jQuery library, you can let it do the searching:
var found = null;
var e = $(divReference).find('a[name=foundItem]');
if (e.length == 1) found = e.get(0);
Use a JavaScript library like jQuery and save yourself time.
var theAnchor = $('#divId a[name=foundItem]');
Using jquery, it's dead easy:
<script type="text/javascript">
$(function(){
var item = $("#yourDivId a[name=foundItem]")
)};
</script>
Update:
As per the comments, if you have control over what to id/name/class your anchor tag/s, it would be best to apply a class to them:
<div id="firstDiv">
test
</div>
<div id="secondDiv">
test another one
</div>
<!-- and so forth -->
<script type="text/javascript">
$(function(){
var item = $("#firstDiv a.foundItem");
alert(item.html()); // Will result in "test"
var item2 = $("#secondDiv a.foundItem");
alert(item2.html()); // Will show "test another one"
)};
</script>
If you're doing anything with javascript, jQuery saves you tons of time and is worth investing the effort to learn well. Start with http://api.jquery.com/browser/ to get an intro to what's possible.
Not sure if this helps, but wanted a function to handle the load of a page dynamically and scroll to the anchor of choice.
function scrollToAnchor(anchor_val) {
alert("" + anchor_val);
var page = document.getElementById('tables');
var found = null;
var cnt = 0;
var e = document.getElementsByTagName('a');
for (var i = 0; i < e.length; i++) {
if (e[i].name && e[i].name == anchor_val) {
found = e[i];
break;
}
cnt++;
}
if (found) {
var nPos = found.offsetTop;
alert("" + nPos);
page.scrollBy(0, nPos);
} else {
alert('Failed with call of scrollToAnchor()' + cnt);
}
}

Categories

Resources