Appending Link To Head Of Iframe - javascript

I want to append element To head of an Iframe (fancybox)
there is a strange problem : when I use Firefox to Breakpoint on line of code that append element to Head it works correctly but when I run site normally without firebug it does not work;
I am using fancybox 1.3.4 and the code run in onComplete event
var cssLink = document.createElement("link")
cssLink.href = "/themes/furniture/css/test.css";
cssLink .rel = "stylesheet";
cssLink .type = "text/css";
var f123= document.getElementById('fancybox-frame');
var d123= f123.contentDocument || f123.contentWindow.document;
d123.head.appendChild(cssLink);
UPDATE
I also try this code
var $head = $("#fancybox-frame").contents().find("head");
$head.append($("<link/>",
{ rel: "stylesheet", href: "/themes/furniture/css/test.css", type: "text/css" } ));
but it does not work either
Tnx

Well, it seems to be a racing condition indeed (as pointed out by olsn in his comment) between loading the iframe and finding elements inside of it, which fails if the second occurs first ;)
As a workaround, you could use the .load() method to wait for the iframe to be completely loaded before trying to append the stylesheet to the <head> section.
This code should do the trick :
$(document).ready(function () {
$(".fancybox").fancybox({
"type": "iframe",
"onComplete": function () {
var $style = '<link rel="stylesheet" href="/themes/furniture/css/test.css" type="text/css" />';
$("#fancybox-frame").load(function () {
$(this).contents().find("head").append($style);
});
}
});
});
Note : this is for fancybox v1.3.4. Fortunately v2.x includes more flexible public methods than v1.3.4 to circumvent this issue, like afterLoad and beforeShow
Also notice that setTimeout() will work too, but it renders oddly.

Related

Featherlight, JavaScript source for dynamic content

I'm evaluating Featherlight lightbox and I'm not able to implement code that satisfies my use case. I need a lightbox that will be used as a report viewer which displays dynamically created content assigned to a JavaScript variable. The value of the string is a valid HMTL5 page.
I've looked at the iframe example, but it depends upon a static iframe being in the DOM. That's not what I need.
I've reviewed this GitHub issue and this jsfiddle and I'm not able to successfully modify the fiddle to display a string.
This is an example of the string I would like to display:
var s = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Title of the document</title></head><body><p>Content of the document......</p></body></html>';
Is this possible and if so how?
I expect that $.featherlight() will be called manually in response to a button click.
The solution I came up with was to modify the Featherlight source code in 2 places as indicated in this block of code (currently around line 383).
iframe: {
process: function(url) {
var deferred = new $.Deferred();
var $content = $('<iframe/>')
.hide()
.attr('src', url)
.attr('id', this.namespace + '-id') // [KT] 10/31/2016
.css(structure(this, 'iframe'))
.on('load', function() {if ($content.show()) {deferred.resolve($content.show()) } else {deferred.resolve($content)} ; }) // [KT] 10/31/2016
// We can't move an <iframe> and avoid reloading it,
// so let's put it in place ourselves right now:
.appendTo(this.$instance.find('.' + this.namespace + '-content'));
return deferred.promise();
}
},
The id attribute is added to the iframe so content can be added by JavaScript, like this:
var s = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Title of the document</title></head><body><p>Content of the document......</p></body></html>';
var oIframe = document.getElementById('featherlight-id'); // Featherlight's iframe
var iframeDoc = (oIframe.contentDocument || oIframe.contentWindow.document);
iframeDoc.open();
iframeDoc.write(s);
iframeDoc.close();
This then works:
$.featherlight({iframe: 'about:blank', iframeWidth: '96%' });
The 2nd modification is required so that the url 'about:blank' doesn't raise an error.
I also modified the css so as to get the scroll bars to work as needed.
Edit: the issue with Featherlight not opening an iframe when the url is abount:blank has been fixed as of version 1.5.1.
Edit 2: Using v1.5.1, this works without having to make a modification to Featherlight to add an id to to the iframe:
var s = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Title of the document</title></head><body><p>Content of the document......</p></body></html>';
$.featherlight({iframe: 'about:blank'});
var $iframe = $('.featherlight iframe');
$iframe.ready(function () {
$iframe.contents().find("body").append(s);
});
The accepted SO answer was used for this solution.

Adding a style sheet IE 8 with JavaScript

I'm making a zoom button to add and remove a CSS file and for some reason I can't seem to add it in IE 8
First I tried this
document.createStyleSheet('style/zoom.css');
given that the jquery solution
$("head").append($("<link my style sheet />"));
seems to only work in FF and IE9 via my testing
I checked around the overflow and found this solution
$('#zoomlink').replaceWith($('<link>', {
id: 'zoomlink',
href: 'style/zoom.css',
type: 'text/css',
rel: 'stylesheet'
}));
But still no love to be found so then frustrated i found this
var $link = $('<link>');
$('head').add($link);
$link.attr({
type: 'text/css',
href: 'style/zoom.css',
type: 'text/css',
rel: 'stylesheet',
media: 'screen'
});
which im not certain would ever work but then finally i decided it way time to simply post a question.
I'm still not certain on how to remove the style sheet later via javascript but I need to first determine how to add a new style sheet in IE 8.
Maybe this will help (Sorry, can't try it in IE8):
(function() {
var s = document.createElement('link');
s.type = 'text/css';
s.rel = 'stylesheet';
s.href = 'http://yourdomain.com/style.css';
document.getElementsByTagName("head")[0].appendChild(s);
})();
To remove it I would assume a simple remove() would work
$("#zoomlink").remove();
To add a new link using jQuery with this syntax:
$("head").append(unescape("%3Clink id='zoomlink' rel='stylesheet' type='text/css' href='style/zoom.css'%3E%3C/link%3E"));
or using pure JavaScript
var e = document.createElement('link');
e.id = 'zoomlink'
e.rel = 'stylesheet';
e.type='text/css';
r.href='style/zoom.css'
document.getElementsByTagName("head")[0].appendChild(e);
There is many other way of writing the same but the idea is the same, remove the old reference element and add a new one.

append element in head of an iframe using jquery

i want to append a style sheet(css) link to the head of an iframe using jquery .
i tried with the following code but not working.
$('#tabsFrame').contents().find("head").append(cssLink);
i am used to append data to an iframe by using this line of code
$('body', window.frames[target].document).append(data);
In your case, this line would look like this
$('head', window.frames['tabsFrame'].document).append(cssLink);
EDIT:
Add <head></head> to the iframe and change your var cssLink to
cssLink = '<link href="cupertino_1.4/css/cupertino/jquery-ui-1.8.7.custom.css" type="text/css" rel="Stylesheet" class="ui-theme" />
well, you can check with this:
$('#tabsFrame').contents().find("head")[0].appendChild(cssLink);
I believe you can't manipulate the content of an iframe because of security.
Having you be able to do such a thing would make cross-site-scripting too easy.
The iframe is totally seperate from the DOM of your page.
Also, java and javascript are two completely different things!
Follow the Link to see the difference here
This could be related to IE not allowing you to add elements in the DOM, check out the clever solution here
EDIT:
Thanks #kris, good advice to add more info in case links break:
Here is the main code snippet from the link, in case it goes out again.
(This is only needed with some IE version, for the most part, the other answer work just fine)
var ifrm;
//attempts to retrieve the IFrame document
function addElementToFrame(newStyle) {
if (typeof ifrm == "undefined") {
ifrm = document.getElementById('previewFrame');
if (ifrm.contentWindow) {
ifrm = ifrm.contentWindow;
} else {
if (ifrm.contentDocument.document) {
ifrm = ifrm.contentDocument.document;
} else {
ifrm = ifrm.contentDocument;
}
}
}
//Now that we have the document, look for an existing style tag
var tag = ifrm.document.getElementById("tempTag");
//if you need to replace the existing tag, we first need to remove it
if (typeof tag != "undefined" || tag != null) {
$("#tempTag", ifrm.document).remove();
}
//add a new style tag
$("HEAD", ifrm.document).append("");
}

JavaScript source file not loading in IE8 Popup

I have an issue where the JavaScript source file is loading in popup for IE6, Chrome, Firefox, Safari and Opera. But the same source file is not loading up in IE8.
As a result of this the HTML is not being replaced in the Popup and I am getting an error in IE8 popup saying tinyMCE is not defined
I have referred to Formatting this JavaScript Line and solved issue on all browsers except IE8.
The JavaScript function is as follows:
function openSupportPage() {
var features="width=700,height=400,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes";
var winId=window.open('','',features);
winId.document.open();
winId.document.write('<html><head><title>' + document.title + '</title><link rel="stylesheet" href="../css/default.css" type="text/css">\n');
var winDoc = winId.document;
var sEl = winDoc.createElement("script");
sEl.src = "../js/tiny_mce/tiny_mce.js";/*TinyMCE source file*/
sEl.type="text/javascript";
winDoc.getElementsByTagName("head")[0].appendChild(sEl);
winId.document.write('<script type="text/javascript">\n');
winId.document.write('function inittextarea() {\n');
winId.document.write('tinyMCE.init({ \n');
winId.document.write('elements : "content",\n');
winId.document.write('theme : "advanced",\n');
winId.document.write('readonly : true,\n');
winId.document.write('mode : "exact",\n');
winId.document.write('theme : "advanced",\n');
winId.document.write('readonly : true,\n');
winId.document.write('setup : function(ed) {\n');
winId.document.write('ed.onInit.add(function() {\n');
winId.document.write('tinyMCE.activeEditor.execCommand("mceToggleVisualAid");\n');
winId.document.write('});\n');
winId.document.write('}\n');
winId.document.write('});}</script>\n');
window.setTimeout(function () {/*using setTimeout to wait for the JS source file to load*/
winId.document.write('</head><body onload="inittextarea()">\n');
winId.document.write(' \n');
var hiddenFrameHTML = document.getElementById("HiddenFrame").innerHTML;
hiddenFrameHTML = hiddenFrameHTML.replace(/&/gi, "&");
hiddenFrameHTML = hiddenFrameHTML.replace(/</gi, "<");
hiddenFrameHTML = hiddenFrameHTML.replace(/>/gi, ">");
winId.document.write(hiddenFrameHTML);
winId.document.write('<textarea id="content" rows="10" style="width:100%">\n');
winId.document.write(document.getElementById(top.document.forms[0].id + ":supportStuff").innerHTML);
winId.document.write('</textArea>\n');
var hiddenFrameHTML2 = document.getElementById("HiddenFrame2").innerHTML;
hiddenFrameHTML2 = hiddenFrameHTML2.replace(/&/gi, "&");
hiddenFrameHTML2 = hiddenFrameHTML2.replace(/</gi, "<");
hiddenFrameHTML2 = hiddenFrameHTML2.replace(/>/gi, ">");
winId.document.write(hiddenFrameHTML2);
winId.document.write('</body></html>\n');
winId.document.close();
}, 300);
}
Additional Information:
Screen shot of the page
Rendered HTML
Original JSPF
please help me with this one.
Why are you using actual DOM functions to add the <script> tag that includes tinymce.js but everything else is using document.write?
I think that's also where your problem lies, as <head> is within <html>, which is not yet closed where you want to append said <script> tag.
Otherwise, you could use the existing <script> tag in the popup to add the code that includes the required external javascript file. If that makes any sense.
So, basically I'm saying, try it the same way as everything else is in your script, using document.write.
(quick addition) I'm not saying this is the 'best' way to do this, I would recommend creating an actual page instead of dynamically creating one in the popup. But in this scenario, I think what I wrote earlier might solve the problem you are having.

How to add anything in <head> through jquery/javascript?

I'm working with a CMS, which prevents editing HTML source for <head> element.
For example I want to add the following above the <title> tag:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
You can select it and add to it as normal:
$('head').append('<link />');
JavaScript:
document.getElementsByTagName('head')[0].appendChild( ... );
Make DOM element like so:
const link = document.createElement('link');
link.href = 'href';
link.rel = 'rel';
document.getElementsByTagName('head')[0].appendChild(link);
jQuery
$('head').append( ... );
JavaScript:
document.getElementsByTagName('head')[0].appendChild( ... );
You can use innerHTML to just concat the extra field string;
document.head.innerHTML = document.head.innerHTML + '<link rel="stylesheet>...'
However, you can't guarantee that the extra things you add to the head will be recognised by the browser after the first load, and it's possible you will get a FOUC (flash of unstyled content) as the extra stylesheets are loaded.
I haven't looked at the API in years, but you could also use document.write, which is what was designed for this sort of action. However, this would require you to block the page from rendering until your initial AJAX request has completed.
In the latest browsers (IE9+) you can also use document.head:
Example:
var favicon = document.createElement('link');
favicon.id = 'myFavicon';
favicon.rel = 'shortcut icon';
favicon.href = 'http://www.test.com/my-favicon.ico';
document.head.appendChild(favicon);
Create a temporary element (e. g. DIV), assign your HTML code to its innerHTML property, and then append its child nodes to the HEAD element one by one. For example, like this:
var temp = document.createElement('div');
temp.innerHTML = '<link rel="stylesheet" href="example.css" />'
+ '<script src="foobar.js"><\/script> ';
var head = document.head;
while (temp.firstChild) {
head.appendChild(temp.firstChild);
}
Compared with rewriting entire HEAD contents via its innerHTML, this wouldn’t affect existing child elements of the HEAD element in any way.
Note that scripts inserted this way are apparently not executed automatically, while styles are applied successfully. So if you need scripts to be executed, you should load JS files using Ajax and then execute their contents using eval().
Try a javascript pure:
Library JS:
appendHtml = function(element, html) {
var div = document.createElement('div');
div.innerHTML = html;
while (div.children.length > 0) {
element.appendChild(div.children[0]);
}
}
Type:
appendHtml(document.head, '<link rel="stylesheet" type="text/css" href="http://example.com/example.css"/>');
or jQuery:
$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', 'http://example.com/example.css'));
With jquery you have other option:
$('head').html($('head').html() + '...');
anyway it is working. JavaScript option others said, thats correct too.

Categories