How to refresh the page on document.write - javascript

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

Related

Adding CSS to new document created by Javascript

I'm trying to create a blank document with Javascript, and then import the CSS file I already have with it.
Here is my code:
function printData() {
let ptimetable = document.getElementById("timetable");
let printWin = window.open("");
printWin.document.write(ptimetable.outerHTML);
let hd = printWin.document.getElementByTagName("head")[0];
let link = printWin.document.createElement("link")
link.rel = "stylesheet";
link.type = "text/css";
link.href = "../css/main.css";
hd.appendChild(link);
//printWin.print();
//printWin.close();
}
I can't figure out what I'm doing wrong - the document is created, but the CSS from my file doesn't apply to the table.
Any help would be much appreciated!
Thanks!
R
After the comments I've seen, the problem resides in the incorrect CSS link. There's also an issue with one of the functions that I have seemingly just made up in my head. Thanks everyone

Microsoft Dynamics 365 Change Header Color on Form based on value

I have an option set on my Account / Sales form. Based on this value I want to change the header color at the top of the form.
I can do this manually through editing the CSS through the Developer Tools, however when I try and do this through Form Properties and Web Resources I cannot get the color to change.
As a base test I'm just trying to inject the CSS into the page through javascript.
Here is the CSS web resource that I created.
.ms-crm-Form-HeaderPosition {
background-color: rgba(2,206,239,1) !important;
}
Here is the javascript web resource I created:
function load_css_file(filename){
var fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
document.getElementsByTagName("head")[0].appendChild(fileref)
}
function myFormOnLoad(){
load_css_file('/WebResources/aws_ColoredHeaderMGA.css');
}
I then went to my Sales form, changed the form properties to load in my Javascript web resource and then told it to call the function myFormOnLoad as on OnLoad even for the form.
I'm not getting any errors, I know the javascript is getting called because I added an alert to it just to make sure and I did receive the alert.
What am I missing to get the header color to change?
In case someone is looking for working code, the below one we are using.
I guess the URL is the problem in OP. Add OrgName & remove extension (.css)
function LdCSS() {
var path = "/orgname/WebResources/new_custom";
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = path;
link.media = 'all';
head.appendChild(link);
}

document.write() for adding a stylesheet causes document to be blank

I am trying to add a stylesheet only on the condition that the browser is either Chrome or Opera. I have the following control flow using the YUI library:
if ((Y.UA.chrome > 0) || (Y.UA.opera > 0)){
document.write("<link rel='stylesheet' media='print' type='text/css' href='../../../css/style_ticket_printing_header.css'/>");
}
Here is the conditionally attached css file, style_ticket_printing_header.css
#page
{
size: auto;
margin: 0mm;
}
Here is the full HTML:
https://gist.github.com/ebbnormal/b1cff9d45914bc2f63a4
When I run the page in Chrome, none of the <div>s that are defined within the <body> tag are rendered or are displayed within the DOM.
What is particularly confusing is that, when this CSS is loaded in the normal way (by simply referencing it via a <link> tag in the <head> of the page, all of the DOM are loaded perfectly.
And finally I know that it successfully renders the condition of seeing it is chrome as I formerly had an alert message in the body of the if block which successfully executed.
document.write() for adding a stylesheet causes document to be blank
Right. When you use document.write after the main page parsing is complete, it implicitly does a document.open, which wipes out the page.
Instead, use createElement and appendChild:
if ((Y.UA.chrome > 0) || (Y.UA.opera > 0)){
var link = document.createElement('link');
link.rel = "stylesheet";
link.media = "print";
link.type = "text/css";
link.href = "../../../css/style_ticket_printing_header.css";
document.querySelector("head").appendChild(link);
}
Or if you really like to use HTML: :-)
if ((Y.UA.chrome > 0) || (Y.UA.opera > 0)){
document.querySelector("head").insertAdjacentHTML(
"beforeend",
"<link rel='stylesheet' media='print' type='text/css' href='../../../css/style_ticket_printing_header.css'/>"
);
}
(Both of the above assume you have a head element, which you presumably do; it's required in a well-formed HTML document, either explicitly or because the browser adds it for you [but explicit is best].)
About querySelector: It finds the first element that matches a CSS selector. It's supported by all modern browsers, and also IE8. (There's also querySelectorAll, which finds a list of matching elements.)
Inside of your <head> tag in html file,
<SCRIPT LANGUAGE="JavaScript">
if ((Y.UA.chrome > 0) || (Y.UA.opera > 0)){
document.write("<LI" + "NK rel='stylesheet' media='print' type='text/css' href='../../../css/style_ticket_printing_header.css'/>");
}
</SCRIPT>
it may work.
Assuming you want to add the stylesheet into the head, take a look at this: Append some HTML into the HEAD tag?
The basic idea is to use
var newElement = document.createElement('element')
and
newElement.setAttribute('attr', 'val')
This will work (as originally suggested by users1100's answer on SharePoint.SE):
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);

Can I display favicon from inside an iframe?

I have another site running inside a webpage as an iframe. However it's not displaying the favicon. I think it's not possible but just wanted to double confirm if someone knows of a way.
May be something like this in your child page i.e. page inside iFrame :
(function() {
var link = parent.document.createElement('link');
link.type = 'image/x-icon';
link.rel = 'shortcut icon';
link.href = 'http://www.stackoverflow.com/favicon.ico';
parent.document.getElementsByTagName('head')[0].appendChild(link);
}());
You can set a favicon by modifying the HTML, i.e. by adding:
<link rel="shortcut icon" type="image/png" href="/favicon.png"/>
to the <head> (or changing the existent link).
You can also access DOM of the top document if both the top document and the iframe are on the same domain.
Example:
master = window.parent.document;
head = master.getElementsByTagName("head")[0];
favicon = master.createElement("link");
favicon.rel = "shortcut icon";
favicon.type = "image/png";
favicon.href = "//cdn.sstatic.net/stackoverflow/img/favicon.ico?v=038622610830";
head.appendChild(favicon);
sets the icon of the page to Stack Overflow favicon.

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