Print via javascript in SharePoint - javascript

I've looked around here and saw wonderful solutions how to print the content of a div using javascript by instantiating a new window and porting markup there.
My problem with that solution in SharePoint is that SP.*.js libraries load asynchronously and it freezes the print dialog screen or the browser itself.
Anybody was able to workaround this issue?

With sharepoint you can use ExecuteOrDelayUntilScriptLoaded to wait until SP.js loaded to make sure nothing freezes.
<script type="text/javascript">
function printPage(){
}
window.onload = function(){ ExecuteOrDelayUntilScriptLoaded(printPage, "sp.js"); };
</script>

I don't know SharePoint specifically, so I can't provide a specific example. However, it sounds like you are thinking of a technique like the one outlined on this other stackoverflow question.
Notice this is all one block of code that will execute sequentially. So we open a window, set the markup and print right away. No waiting around between those steps.
I would suggest that you don't call print at that point, but rather open the window, set the markup AND inject some more javascript in the new window markup. This new injected javascript will be where the actual printing takes places.
That injected script should have some logic to wait until certain script resources have finished loading after which it calls window.print(). Apparently window.onload doesn't fire until after all resources have finished loading. (onload doesn't fire until all content is either loaded or has failed to load). Here's a jquery example on stackoverflow. Also scripts are executed in the order the appear in the markup. So if your injected print window javascript is last, every other script above it must already be done. (So anything SharePoint injects in the markup should already have been executed).
For bonus points, if everything is going well, you could inject a 'loading mask' over the new print window and then hide the mask just before your javascript does its window.print().

The code given below will work with sharepoint, ASPX pages and with any browser. I tested the code with Sharepoint 2010 Visual webparts, and it works like a charm.
Place this Javascript code inside your webpart ASCX file
<script type="text/javascript">
function printPartOfPage(elementId) {
var printContent = document.getElementById(elementId);
var windowUrl = '';
var uniqueName = new Date();
var windowName = 'Print' ;
var printWindow = window.open(windowUrl, windowName, 'left=-20,top=-20,width=0,height=0');
printWindow.document.write('<HTML><Head><Title></Title>');
printWindow.document.write('</Head><Body style="margin-left:50px;margin-top:50px;font-size:10pt;">');
printWindow.document.write(printContent.innerHTML);
printWindow.document.write('</Body></HTML>');
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();
}
</script>
& Update the print button ClientClick Event with
<img alt="" src="~/_layouts/images/WebpartCollection/Printer-30X30.jpg"
onclick="JavaScript:printPartOfPage('YourDivClientID');" />
I hope this will help you out.

Related

How to use a .js file to display a webpage using document.write()

I'm sure this is obvious but its driving me crazy. I have an assignment where we create an order form page. The last part of it involves making a conformation page display after the user enters their information. We are supposed to use document.write() to create the webpage in a function called displayOutput(), which is called by a previous function. My problem is that I have no idea how to build a webpage using document.write(). Nothing i've put in the displayOutput() function writes to the page. All that happens is the original order form page pops up. What am I not doing?
Here's a tiny chunk of my displayOutput() function.
document.write("<body>");
document.write("<div id='container'>");
document.write("<div id='header'>");
displayHeader();
document.write("</div>");
document.write("</div>");
document.write("</body>");
Also, please remember I HAVE to use document.write()
Open a new window and apply document.write method with that reference. Use window.open(URL,name,specs,replace) method.
For example: myWindow is a reference of new window here.
<script>
var myWindow = window.open("", "_self");
myWindow.document.write("<body><div id='container'><div id='header'>"+displayHeader()+"</div></div></body>");
</script>
If you want to open this window on new page, replace _self with _blank etc.
Hope, it will work for you.

Javascript pop-up login cross-browser issue

I have a page with an iframe in it. Within the iframe, the default page runs some javascript to open a child window, login to an external service, then display some content from that external service back in the iframe.
My code works fine in Chrome and IE but in Safari and Firefox it does not. In those browsers the parent window seems to ignore that fact that the user is now logged in to the external service and displays their "Not logged in" message instead of the info that is supposed to display.
Here's the code for what I'm trying to do.
HTML (main page):
<iframe id="brief" name="brief" src="contents/somepage.php?var=WXYZ" width="962" height="600">
<p>Your browser does not support iframes.</p>
</iframe>
somepage.php
<html>
<head>
<script type="text/javascript">
window.onload = function()
{
var code = 'WXYZ';
var login = http://www.externalsite.com/brief/html.asp?/cgi-bin/service?msg=0048&usr=username&pwd=pass';
//OPEN CHILD WINDOW AND LOGIN USING VARIABLES ABOVE, THEN CLOSE WINDOW
childWindow=window.open(login,'','width=30,height=30,location=no');
var cmd = 'childWindow.close()';
setTimeout(cmd,2000);
//REDIRECT THIS IFRAME TO BRIEFING INFORMATION
var uri = 'http://www.externalsite.com/brief/html.asp?/cgi-bin/service?msg=0092&AID=NOSEND&MET=1&NTM=1&LOC='+code;
self.location.href=uri;
}
</script>
</head>
<body>
</body>
</html>
I have tried adjusting various setTimeout functions to try to delay certain aspects of the script to wait for something else to happen but it doesn't seem to help.
Is there some cross-browser problem with this code that I am missing?
Thanks
setTimeout(cmd,2000); is not going to block script execution for two seconds; rather, it sets up an event that will fire in approximately 2 seconds. Immediately after your call to setTimeout, the remaining parts of the script will execute:
// This happens right away
uri = 'http://www.externalsite.com/brief/html.asp?/cgi-bin/service?msg=0092&AID=NOSEND&MET=1&NTM=1&LOC='+code;
self.location.href = uri;
The fact that it works in any browser is just lucky timing. If you want the iframe to refresh after the popup closes, add that code to your callback (you don't need to and shouldn't use a string for your timer handler, by the way):
setTimeout(function() {
childWindow.close();
var uri = 'http://www.externalsite.com/brief/html.asp?/cgi-bin/service?msg=0092&AID=NOSEND&MET=1&NTM=1&LOC='+code;
self.location.href = uri;
}, 2000);
Even this solution won't work if the popup's content doesn't load within two seconds. The best solution is to have the popup close itself after loading. Then, you could detect when it closes and know that you're ready to reload your iframe. But if this is a third-party site that you don't have control over, you're probably stuck using a less-than-ideal solution like this.

asp.net / javascript: How to open a link in a new web page set to a width 640px and height 480px?

Morning All,
I was hoping someone could help or provide some sample code for me in refe to the following. I not too sure if i can simply set the asp.net (Visual Studio 2010) properties or if i need some java script to complete my task.
I have a web page with a link on it that when users click it opens to a new web page via the _Blank command.
What i would like to do is have this page open on a really small scale (640px X 480px) and layerd on top of the main webpage. This small page essentially just holds a gridview with items listed for documentation.
I have looked around the internet as i think this would be best done by using JavaScript in the smaller web page but i cant get this to work successfully.
I have found a sample and need to try and tweak this but have been unsuccessfull.
Here is the sample code i have....
<script type="text/javascript" language="javascript">
window.onload = function () {
var w = window.open("about:blank", "main", "width=640,height=480", true)
window.opener = "main";
window.open("", "_parent", "");
w.opener.close();
}
</script>
My smaller web page is named uploadview.aspx
Any help is advenace is much appriechiated.
Regards
Betty
You got to specify window URL in first param of window.open, and must have button to invoke that JavaScript, it's not clear why do you do that on page load event. Anyway, here is the example to open window on some link click
Open Upload View
<script type="text/javascript">
function OpenUploadView() {
window.open("uploadview.aspx?param=1", "_blank", "width=640,height=480", true);
}
</script>
You can also pass parameters to that aspx page like shown above.
You can use window.opendialog()
For more visit https://developer.mozilla.org/en/DOM/window.openDialog

Javascript set title onload?

Is there anyway to set the title of a website via JS onload? I wrote this but I'm not sure where it's incorrect:
function my_code(){
document.title = "The new title goes here.";
}
window.onload=my_code();
The page title is static by the way.
Edit: The reason why I want to do it this way is because I'm writing a Safari Extension for a website that does not include tags so I wanted to insert one via JS.
You don't need to wait for the load event.
Just write document.title = ... anywhere.
If you want to change the title after the page loaded, you have to assign a function reference to onload (your function assigns the return value of my_code):
window.onload = my_code;
However, you most certainly can set the title without waiting for the load event.
I'm not familiar with Safari extensions, but you should also make sure that window actually refers to the page's window.

Browser refresh on AJAX with script tags in the response

I'm having some issues with a jQuery AJAX call. My code works fine when I request a page with no javascript in it, but when I have script tags in my code, things start to get weird.
It seems that any script tags referencing external URLs cause the browser to redirect. In firefox, the page goes blank. In safari, the page clears and loads with the content of the AJAX response. In both browsers, the URL doesn't change.
To be specific about my problem; I have a tab control in which I'm trying to embed the walkscore widget. Since it's pretty heavy on the client side, I only want to actually load it once the user clicks the tab it's in. The walkscore AJAX page looks like this:
<script type="text/javascript">
var ws_address = "1 Market St, San Francisco";
var ws_width = "500";
</script>
<script type="text/javascript" src="http://www.walkscore.com/tile/show-tile.php?wsid=MY_WSID">
</script>
Is there some restriction on script tags referencing external sites on AJAX calls? Is there any nice way around this?
-- Edit --
OK I've been playing with it for a bit and have narrowed down the problem a little. Let me try give a better explanation at the same time:
I have two files, index.html and walkscore.html
index.html
function widget() {
var widget = $('#walkscore');
$.get('/walkscore.html', function(data) {
$('#loading').slideUp(function() {
widget.html(data);
loaded[name] = true;
widget.slideDown();
});
});
}
walkscore.html - as shown in the top code block
In index.html, I have a link that calls the widget function. Whenever I click this link, the whole page is replaced by the output of the js file. It happens regardless of the domain the js file is from. It only seems to happen with js files that have document.write in them. It behaves in exactly the same way when I use the $.getScript function, even when it's in index.html
-- Edit --
It seems it has everything to do with the document.write. I made a copy of the walkscore javascript and replaced all occurrences of document.write with jquery.html, and it seems to work properly. I'm (obviously) a js noob. Is this the expected behavior of document.write? How come it doesn't do it when I include the script on a page load?
Load script separately from html content, you can use $.getScript( ).
It has to do with the document.write in the response.. I was able to fix this in Firefox by doing this:
<script type="text/javascript">
// save default document.write function so we can set it back
var write_func_holder = document.write;
// redefine document.write to output text target div
document.write = function(text) {
$('#ad_container').html($('#ad_container').html() + text);
}
</script>
<script language="JavaScript" type="text/javascript" src="javascriptfile">
</script>
<script type="text/javascript">
// reset document.write function
document.write = write_func_holder;
</script>
I'm still getting an issue in Safari where the browser refreshes to a blank page with just the content of the document.write and IE6, IE7 doesn't do anything at all. Firefox works though.
I hope this helps someone figure out what wrong and they in turn can fix the IE6/7 and Safari issues
It happens because of the document.write call. Here's some info on what's going on:
Writing After A Page Has Been Loaded
If document.write() is invoked after a page has finished loading, the entire static (non-script generated) content of a page will be replaced with the write method's parameter. This scenario is most often played out when the write method is invoked from an event handler - whether the method is in a function called by the event handler or alone inside the handler - because event handlers are triggered after a page has finished loading. This is important to know because static content replacement is not always the desired result. Another common scenario for content overwite has to do with writing content to a new window. In this case, the overwrite of blank page is the goal.
(source)
The solution I went with was to eliminate the document.write commands, and replace the content of a div instead. If you're loading an external script, and have no control over it, you can replace the document.write function with your own. It's discussed here:
http://www.webxpertz.net/forums/showthread.php?threadid=11658
Hope that helps someone out there!
Replacing document.write is the way to go. This is shameless self promotion, but if you have a non-trivial case, writeCapture.js handles all the edge cases.
I would first check the response of that script source, maybe something in that causes the unwanted behavior.
I am experiencing the EXACT same behaviour and spent some frustrating hours last night trying to figure out what the problem was and searching for answers to no avail. I'm surprised this is mentioned anywhere in the jquery docs as it seems like a plausible problem not some crazy never-to-be-encountered bug.
Anyway, here's my story in case anyone searches for something related.
I have a jquery enabled page that loads some content into a div using $.ajax(), it all works perfectly. What I needed to do was include one of those twitter retweet buttons that shows a count and enables you to tweet about the content on the page. To do this a simple piece of javascript from them should be included on the page.
<script type="text/javascript" src="http://www.retweet.com/static/retweets.js"></script>
So in theory, that script tag should be returned in the ajax call and jquery should execute it and include the result of it, as I specified the data type as html in the $.ajax() call.
The external script on closer inspection does:
if(!url)
{
var url=window.location.href;
}
if(!size)
var size="big";
var height="75";
var width="54"
if(size=="small")
{
height="22";
width="120";
}
if(!username)
var username="none";
url=url.replace("?", "*");
var src="http://www.retweet.com/widget/button/"+size+"/"+username+"/"+url;
document.write('<iframe src="'+src+'" height="'+height+'" width="'+width+'" frameborder="0" scrolling="no"></iframe>');
Which obviously bombs out on the document.write.
Tonight i'll try the methods in this post and see if they work, thanks for the info.

Categories