Why document.styleSheets[0].href doesn't get updated? - javascript

Why document.styleSheets[0].href doesn't get updated but document.getElementsByTagName('link')[0].href does, when I dynamically create a <base/> tag?
On Opera it works fine, but Firefox and Chrome don't update the value.
Here is the code, you can run it on http://jsfiddle.net/XcDCk/.
If you don't run it on jsfiddle.net you must add a linked stylesheet (<link rel="stylesheet" type="text/css" href="styles.css"/>)
var base = document.createElement('base');
base.href = 'http://google.com/';
document.getElementsByTagName('head')[0].appendChild(base);
var link = document.getElementsByTagName('link')[0];
alert('Link: '+link.href);
var styleSheet = document.styleSheets[0];
alert('Stylesheet: '+styleSheet.href);
var hojaEstilos = document.styleSheets[0];
alert('Stylesheet + ownerNode: '+hojaEstilos.ownerNode.href);
I could get it done (on the third alert) by using the ownerNode attribute (which is actually the link element, so I can get the same result as the first alert), but I can't understand why the second alert doesn't work.
Thank you

Related

Chrome sometimes not requesting CSS pages

This is an ASPX page and rarely the stylesheets do not load. No Request either. I can look at the network log in chromes debug and see that it didnt request it or load it from cache. Everything else, img , js, whatever all loads without problem. The only thing that this site does that I have never done before is load a stylesheet via javascript and that will request and work every time. There is also an Iframe in the page and that css always works as well. It feels like a 1 in 10 chance for this to happen, but its random. I cant remember if it happens when i run it locally or not, but it will happen on the 3 different IIS servers. In the sources of the Chrome DevTools it shows the file in there as well. Is this a bug in chrome or something? Is it a weird thing with closing tag in the links? Has anyone seen this before?
<head>
....
<link type="text/css" rel="stylesheet" href="~/css/site.min.css?v=#Model.buildTag" />
<link href="~/lib/tabulator/css/tabulator.css" rel="stylesheet" />
<link id="glcss" type="text/css" rel="stylesheet" href="/css/empty.css">
</head>
This JS code runs mid way trough the initial js load of the page before doc render and it sets a stylesheet to the page. Not sure if this would cause chrome to randomly abandon the other css documents. This css always works.
var stylesheetPath = _pth + "/css/custom_gl_theme_" + dd.value + ".min.css?v=" + _v;
$('link[id="glcss"]').attr('href', stylesheetPath);
this.value = dd.value;
Still don't know the cause, but this is the solution we had put in place. Basically, once the page loads, we check to see if those css files loaded properly, and if not, reset the url and it would force the pull.
$(window).on('load', function (e) {
var links = document.getElementsByTagName('link');
for (var i = 0, linkLen = links.length; i < linkLen; i++) {
var link = links[i];
if ((link.id == "") && (link.type == "text/css")) {
var cssHref = link.href;
link.href = cssHref;
}
}
});

How to refresh the page on document.write

I am using document.write in a function to give different CSS to user's based on their choosing.
function blue() {
document.write('<link rel="stylesheet" type="text/css" href="http://ilam.irib.ir/documents/697970/237563314/blue.css" />');
}
I am calling the function from an anchor tag.
function color2(){
document.getElementById("navigation").innerHTML +='<a class="myButton" onclick="blue()" background-color:"#05c8f2";></a>';
}
As you can guess, when the link is clicked, the page clears out and I get a blank page.
Is there any way to fix this problem? I don't want to stop page refreshing, I'm just trying to fix the problem in any way possible!
Note: don't ask why I'm adding code using JavaScript, and not directly into HTML code. This site is a large scale system and we just have access to JavaScript and CSS. So this is all we can do to edit our pages.
document.write rewrites the body , as a result the only thing in your document remains is the css file you added and hence it is blank.
View this
Code from above link :-
var cssId = 'myCss'; // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://website.com/css/stylesheet.css';
link.media = 'all';
head.appendChild(link);
}
Instead of rewriting while dom , we append the link element inside head tag

How can one identify the currently clicked link with Javascript?

I am using Internet Explorer.
I added a context menu item (through the registry) such that when right clicking on a link in a webpage a custom menu item pops up. Upon selection, this menu item runs some javascript code.
I want to use the url of the link (on which I right click) in the javascript code - how do I access that url?
*Note that this should work for any webpage, not only ones which I have control over.
Thanks in advance!
<script language="JavaScript">
var parentwin = external.menuArguments;
var doc = parentwin.document;
var url = doc.URL;
// ... the rest of your code here ...
See also.
To get the source object, try:
<script language="JavaScript">
var parentwin = external.menuArguments;
var srcElement = parentwin.event.srcElement;
if (srcElement.tagName == "A") {
var url = srcElement.href;
// ... the rest of your code here ...
}

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.

Categories