Have to apply CSS from a hosting site through JavaScript - javascript

I have an iframe, and onLoad am applying css through javascript. This iframe contains data from website A and hosted on website B. The javascript that applies css will be included in the iframe and the css values (to change color of html elements) will be passed by website B.
I have written javascript and like this; please help if there are any suggestions to achieve this or any improvements will be appreciated.
The script on SiteA:-
/* this variable values will be set by site B */
JS
var iframeCSSParams = {
links: "blue",
companyName: "blue",
searchButtonColor: "darkcyan",
fontsColor: "blue"
so on..
};
function applycss(iframe, CSSParams) {
var linksColor = CSSParams.links;
var companyNameColor = CSSParams.companyName;
var searchButtonColor = CSSParams.searchButtonColor;
jQuery(iframe).contents().find('.alinks').css('color', linksColor);
jQuery(iframe).contents().find('.p-company-name').css('color', companyNameColor);
and so on...
}
function Iframe_Load(iframe) {
try {
var doc = iframe.contentDocument || iframe.contentWindow.document;
applycss(iframe, iframeCSSParams);
} catch (e) {
alert('exception: ' + e);
}
}
HTML
<iframe id="listFrame" scrolling="NO" style="padding:0; width:626px;" frameborder="0"
src="/siteA/search" onload="Iframe_Load(this)" />

Related

HTML/JavaScript: How to copy text from a iframe

I'm kinda new to web development. I'm trying to copy text from a iframe into a textarea on a Bootstrap-html webpage.
An example of my code is here: https://jsfiddle.net/fe5ahoyw/
JavaScript
I have tried:
var a = document.getElementById('LD1');
var b = document.getElementById('OD1');
if (a != null)
{
b.value = a.value;
}
I have also tried:
var a = document.getElementById('LD1').innerHTML;
var a = document.getElementById('LD1').value;
var a = document.getElementById('LD1').html;
Any help would be any help would be much appreciated
Frostie
The JSFiddle is currently trying to access a http resource. As JSFiddle itself is https, most browsers will not like this very much.
That said, the selectors you are using inside the code are ... off. You need to get the frame itself -> content of the frame -> element within the frame you are interested in. I'd suggest using something like:
var a = document.getElementById('OD1');
var iFrame = document.getElementById('LD1');
var iFrameDocument = iFrame.contentDocument || iFrame.contentWindow.document;
content = iFrameDocument.body.textContent;
alert(content);
if (content)
{
a.value = content.value;
}

How to load iframe content correctly in to <div in main page (same domain iframe)?

I got an ifram that has many links in it and i am trying to copy those link correctly to my main page. My current code copy the links incorectly .For example if the
actual hyper link is like this in iframe:
5
after coping it in to main page the hyper links become like this :
http://ok.mysite24.com/spring/./ok/doit.php
so after clicking to those links from within my main page i go to dead links instead of actual links. is there away to fix this problem by copying iframe content correctly or should i modify my iframe content ?
<script type='text/javascript'>
function getFrameContents(){
var iFrame = document.getElementById('myframe');
var iFrameBody;
if ( iFrame.contentDocument )
{ // FF
iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
}
else if ( iFrame.contentWindow )
{ // IE
iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
}
alert(iFrameBody.innerHTML);
document.getElementById('response').innerHTML = iFrameBody.innerHTML
}
</script>
<iframe id ='myframe' src='http://www.mysite.com/ok.php'></iframe>
<div id="response">
<p>getFrameContents! </p>
Before retrieving the innerHTML loop over all links and replace their DOM-href-attribute with their JS-href-property. This will turn the href-attributes into absolute URIs.
//clone the body to keep the original untouched
iFrameBody = iFrameBody.cloneNode(true);
var links = iFrameBody.getElementsByTagName('a');
for (var i = 0; i < iFrameBody.getElementsByTagName('a').length; ++i) {
if (links[i].hasAttribute('href')) {
links[i].setAttribute('href', links[i].href);
}
}
It looks like you want to resolve one relative address to the iframe's source address, which may also be relative. Psuedo code (ish):k
function resolveAddress(source, link) {
if(link.indexOf("../") == 0) {
index--; // go up one directory .//
return resolveAddress(source.substr(0,source.lastIndexOf("/")-1),
link.substr(1, link.length-1));
}
else if(link.indexOf("./") == 0) {
// reduce to current directory ./
return resolveAddress(source.substr(0,source.lastIndexOf("/"),
link.substr(2, link.length-1));
}
return source + link;
}
frame_src = "http://www.mysite.com/ok.php"
link = "./ok/doit.php";
resolveAddress(frame_src, link);
//=> "http://www.mysite.com/ok/doit.php"

Trouble with iFrame.contentDocument

Basically, im making a javascript to refresh a page and it will find the price and buy the item when it goes up for the price desired.
I got it to work without the iframe, but I need to to work in the iframe, which is the problem ive reached.
If you went to this page: [ http://m.roblox.com/items/100933289/privatesales ]
and ran this code:
alert(document.getElementsByClassName('currency-robux')[0].innerHTML);
You would get an alert for the lowest price. In the code, this doesnt work (Hence, my problem.)
Try running the code below on this page to get it to work [ http://www.roblox.com/Junk-Bot-item?id=100933289 ]
var filePath = document.URL;
var itemid = filePath.slice(((filePath.search("="))+1));
var mobileRoot = 'http://m.roblox.com/items/';
var mobileEnd = '/privatesales';
var mobileFilePath = mobileRoot+itemid+mobileEnd;
var iframe2 = '<iframe id="frame" width="100%" height="1" scrolling="yes"></iframe>';
document.write(iframe2);
var iframe = parent.document.getElementById("frame");
iframe.height = 300;
iframe.width = 500;
iframe.src = mobileFilePath;
var price;
var snipe = false;
var lp = Number(prompt("Snipe Price?"));
document.title = "Sniping";
function takeOutCommas(s){
var str = s;
while ((str.indexOf(",")) !== -1){
str = str.replace(",","");
}
return str;
}
function load() {
if (snipe == false) {
tgs = iframe.contentDocument.getElementsByClassName('currency-robux');
price = Number((takeOutCommas(tgs[0].innerHTML)));
alert(price);
}
}
iframe.onload = load;
You might try having both pages — the one from "m.roblox.com" and the one from "www.roblox.com" — add the following up at the top of the head:
<script>
document.domain = "roblox.com";
</script>
Code from the different domains won't be allowed to look at each others page contents, but if you set the domains to the same suffix then it should work.
If you can't get it to work by sharing the same document.domain="roblox.com" code then you can try posting messages to the iframe.
Put this inside the iframe page:
window.addEventListener('message',function(e) {
});
In the parent page execute this to pass a message (can be a string or object, anything really) to the iframe:
document.getElementById("frame").contentWindow.postMessage({ "json_example": true }, "*");
Put this in the parent to listen for the message:
window.addEventListener("message", messageReceived, false);
function messageReceived(e) {
}
From inside the iframe posting a message back out:
window.parent.postMessage('Hello Parent Page','*');

Height Listener, jQuery

I'm creating a rich text editor.
Basically I have an iframe with design mode enabled. I'd like it to automatically resize when the user get near the bottom of the iframe while typing, or pasting text.
I have the function to change size.
function changeHeight() {
$(iframe).height($(iframe.contentWindow.document).height());
}
I just need to add a listener. I can't for the life of me find one that works!
Any ideas?
Much appreciated
-Will
Do this: http://sonspring.com/journal/jquery-iframe-sizing and add an onkeypress listener to check for resize.
Fair warning: if the content is not within the same domain --- it will NOT work due to XSS vulnerability prevention (you cannot trap the keypress event in this case).
This has been tested in IE7 to work, should work across most browsers. You're not actually attaching to the iFrame itself either, so much as the element you're interested in (which could very well be the body).
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#IFRAME').contents().find('textarea').bind('keypress', function() {
//Dostuff
})
});
</script>
<iframe src="/whatever.html" width="800" height="400" id="IFRAME" ></iframe>
Where you have a textarea (or div, or whatever) inside the iframe ... change the filter to your heart's content. Iframe resize code shows up in the sonspring article.
**
Edit again for code that attaches to IFRAME directly
Source [only replaced jQuery functions for native DOM. I'll clean out what I can when I have more time]:
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_25589672.html
**
<script>
$(document).ready(function() {
var f = $('#IFRAME')[0];
var fwin = f.contentWindow || f.contentDocument;
fwin.document.designMode = 'on';
var evt_key = function(e) {
e = e || fwin.event;
var range = null, ret = null;
if (fwin.document.selection) {
range = fwin.document.selection.createRange();
ret = range.parentElement();
}
else if (fwin.window.getSelection) {
var range = fwin.window.getSelection().getRangeAt(0);
ret = range.commonAncestorContainer.parentNode || fwin.document;
}
fwin.parent.eventCallback();
};
if (fwin.document.attachEvent) {
fwin.document.attachEvent('onkeypress', evt_key);
}
else if (fwin.document.addEventListener) {
fwin.document.addEventListener('keypress', evt_key, false);
}
})
function eventCallback() {
alert('Key Pressed');
}
</script>
<iframe src="#" width="800" height="400" id="IFRAME" ></iframe>

Update iframe body color after load

I have a page ,page1.html that loads page2.html via an iframe . I need to change the body color of the iframe page (page2.html) to override the CSS style that's loaded on page2.html.
(both pages are on same domain). How can that be updated via Javascript ?
A bit of googling turn up this:
Scripting IFrames
It suggests window.frames[iframeName].document should work.
Since both pages lives on the same domain it should be easy.
Try this,
var changeIFrameBodyColor = function()
{
var iFrame = document.getElementById('iFrame');
var iFrameBody;
if ( iFrame.contentDocument )
{ // DOM
var iFrameBody = iFrame.contentDocument.getElementdByTagName('body')[0];
}
else if ( iFrame.contentWindow )
{ // IE
var iFrameBody = iFrame.contentWindow.document.getElementdByTagName('body')[0];
}
iFrameBody.style.color = '#ff0000';
}
Change Color
<iframe id="iFrame" src="page2.html" ../>

Categories