PageSourceSearch

https://siit.co/blog/unicamp-4437.kxcdn.com/main/wp-content/plugin…/assets/libs/print/jQuery.print.js

js siit.co collected 2026-09-24 09:31:02 UTC 10,878 bytes, 316 lines download raw bytes

1/* @license 
2 * jQuery.print, version 1.6.2
3 * Licence: CC-By (http://creativecommons.org/licenses/by/3.0/)
4 *--------------------------------------------------------------------------*/
5(function($) {
6  'use strict';
7
8  // A nice closure for our definitions
9
10  function jQueryCloneWithSelectAndTextAreaValues(
11      elmToClone, withDataAndEvents, deepWithDataAndEvents) {
12    // Replacement jQuery clone that also clones the values in selects and textareas as jQuery doesn't for performance reasons - https://stackoverflow.com/questions/742810/clone-isnt-cloning-select-values
13    // Based on https://github.com/spencertipping/jquery.fix.clone
14    var $elmToClone = $(elmToClone),
15        $result = $elmToClone.clone(withDataAndEvents, deepWithDataAndEvents),
16        $myTextareas = $elmToClone.find('textarea').
17            add($elmToClone.filter('textarea')),
18        $resultTextareas = $result.find('textarea').
19            add($result.filter('textarea')),
20        $mySelects = $elmToClone.find('select').
21            add($elmToClone.filter('select')),
22        $resultSelects = $result.find('select').add($result.filter('select')),
23        $myCanvas = $elmToClone.find('canvas').
24            add($elmToClone.filter('canvas')),
25        $resultCanvas = $result.find('canvas').add($result.filter('canvas')),
26        i, l, j, m, myCanvasContext;
27
28    for (i = 0, l = $myTextareas.length; i < l; ++i) {
29      $($resultTextareas[i]).val($($myTextareas[i]).val());
30    }
31    for (i = 0, l = $mySelects.length; i < l; ++i) {
32      for (j = 0, m = $mySelects[i].options.length; j < m; ++j) {
33        if ($mySelects[i].options[j].selected === true) {
34          $resultSelects[i].options[j].selected = true;
35        }
36      }
37    }
38    for (i = 0, l = $myCanvas.length; i < l; ++i) {
39      // https://stackoverflow.com/a/41242597
40      myCanvasContext = $myCanvas[i].getContext('2d');
41      if (myCanvasContext) {
42        $resultCanvas[i].getContext('2d').drawImage($myCanvas[i], 0, 0);
43        $($resultCanvas[i]).
44            attr('data-jquery-print', myCanvasContext.canvas.toDataURL());
45      }
46    }
47    return $result;
48  }
49
50  function getjQueryObject(string) {
51    // Make string a vaild jQuery thing
52    var jqObj = $('');
53    try {
54      jqObj = jQueryCloneWithSelectAndTextAreaValues(string);
55    } catch (e) {
56      jqObj = $('<span />').html(string);
57    }
58    return jqObj;
59  }
60
61  function printFrame(frameWindow, content, options) {
62    // Print the selected window/iframe
63    var def = $.Deferred();
64    try {
65      frameWindow = frameWindow.contentWindow || frameWindow.contentDocument ||
66          frameWindow;
67      try {
68        frameWindow.resizeTo(window.innerWidth, window.innerHeight);
69      } catch (err) {
70        console.warn(err);
71      }
72      var wdoc = frameWindow.document || frameWindow.contentDocument ||
73          frameWindow;
74      if (options.doctype) {
75        wdoc.write(options.doctype);
76      }
77      wdoc.write(content);
78      try {
79        var canvas = wdoc.querySelectorAll('canvas');
80        for (var i = 0; i < canvas.length; i++) {
81          var ctx = canvas[i].getContext('2d');
82          var image = new Image();
83          image.onload = function() {
84            ctx.drawImage(image, 0, 0);
85          };
86          image.src = canvas[i].getAttribute('data-jquery-print');
87        }
88      } catch (err) {
89        console.warn(err);
90      }
91      wdoc.close();
92      var printed = false,
93          callPrint = function() {
94            if (printed) {
95              return;
96            }
97            // Fix for IE : Allow it to render the iframe
98            frameWindow.focus();
99            try {
100              // Fix for IE11 - printng the whole page instead of the iframe content
101              if (!frameWindow.document.execCommand('print', false, null)) {
102                // document.execCommand returns false if it failed -http://stackoverflow.com/a/21336448/937891
103                frameWindow.print();
104              }
105              // focus body as it is losing focus in iPad and content not getting printed
106              $('body').focus();
107            } catch (e) {
108              frameWindow.print();
109            }
110            frameWindow.close();
111            printed = true;
112            def.resolve();
113          };
114      // Print once the frame window loads - seems to work for the new-window option but unreliable for the iframe
115      $(frameWindow).on('load', callPrint);
116      // Fallback to printing directly if the frame doesn't fire the load event for whatever reason
117      setTimeout(callPrint, options.timeout);
118    } catch (err) {
119      def.reject(err);
120    }
121    return def;
122  }
123
124  function printContentInIFrame(content, options) {
125    var $iframe = $(options.iframe + '');
126    var iframeCount = $iframe.length;
127    if (iframeCount === 0) {
128      // Create a new iFrame if none is given
129      $iframe = $('<iframe height="0" width="0" border="0" wmode="Opaque"/>').
130          prependTo('body').
131          css({
132            'position': 'absolute',
133            'top': -999,
134            'left': -999,
135          });
136    }
137    var frameWindow = $iframe.get(0);
138    return printFrame(frameWindow, content, options).done(function() {
139      // Success
140      setTimeout(function() {
141        // Wait for IE
142        if (iframeCount === 0) {
143          // Destroy the iframe if created here
144          $iframe.remove();
145        }
146      }, 1000);
147    }).fail(function(err) {
148      // Use the pop-up method if iframe fails for some reason
149      console.error('Failed to print from iframe', err);
150      printContentInNewWindow(content, options);
151    }).always(function() {
152      try {
153        options.deferred.resolve();
154      } catch (err) {
155        console.warn('Error notifying deferred', err);
156      }
157    });
158  }
159
160  function printContentInNewWindow(content, options) {
161    // Open a new window and print selected content
162    var frameWindow = window.open();
163    return printFrame(frameWindow, content, options).always(function() {
164      try {
165        options.deferred.resolve();
166      } catch (err) {
167        console.warn('Error notifying deferred', err);
168      }
169    });
170  }
171
172  function isNode(o) {
173    /* http://stackoverflow.com/a/384380/937891 */
174    return !!(typeof Node === 'object' ? o instanceof Node : o && typeof o ===
175        'object' && typeof o.nodeType === 'number' && typeof o.nodeName ===
176        'string');
177  }
178
179  $.print = $.fn.print = function() {
180    // Print a given set of elements
181    var options, $this, self = this;
182    // console.log("Printing", this, arguments);
183    if (self instanceof $) {
184      // Get the node if it is a jQuery object
185      self = self.get(0);
186    }
187    if (isNode(self)) {
188      // If `this` is a HTML element, i.e. for
189      // $(selector).print()
190      $this = $(self);
191      if (arguments.length > 0) {
192        options = arguments[0];
193      }
194    } else {
195      if (arguments.length > 0) {
196        // $.print(selector,options)
197        $this = $(arguments[0]);
198        if (isNode($this[0])) {
199          if (arguments.length > 1) {
200            options = arguments[1];
201          }
202        } else {
203          // $.print(options)
204          options = arguments[0];
205          $this = $('html');
206        }
207      } else {
208        // $.print()
209        $this = $('html');
210      }
211    }
212    // Default options
213    var defaults = {
214      globalStyles: true,
215      mediaPrint: false,
216      stylesheet: null,
217      noPrintSelector: '.no-print',
218      iframe: true,
219      append: null,
220      prepend: null,
221      manuallyCopyFormValues: true,
222      deferred: $.Deferred(),
223      timeout: 750,
224      title: null,
225      doctype: '<!doctype html>',
226    };
227    // Merge with user-options
228    options = $.extend({}, defaults, (options || {}));
229    var $styles = $('');
230    if (options.globalStyles) {
231      // Apply the stlyes from the current sheet to the printed page
232      $styles = $('style, link, meta, base, title');
233    } else if (options.mediaPrint) {
234      // Apply the media-print stylesheet
235      $styles = $('link[media=print]');
236    }
237    if (options.stylesheet) {
238      // Add a custom stylesheet(s) if given
239      if (!(($.isArray ? $.isArray : Array.isArray)(options.stylesheet))) {
240        options.stylesheet = [options.stylesheet];
241      }
242      for (var i = 0; i < options.stylesheet.length; i++) {
243        $styles = $.merge($styles,
244            $('<link rel="stylesheet" href="' + options.stylesheet[i] + '">'));
245      }
246    }
247    // Create a copy of the element to print
248    var copy = jQueryCloneWithSelectAndTextAreaValues($this, true, true);
249    // Wrap it in a span to get the HTML markup string
250    copy = $('<span/>').append(copy);
251    // Remove unwanted elements
252    copy.find(options.noPrintSelector).remove();
253    // Add in the styles
254    copy.append(jQueryCloneWithSelectAndTextAreaValues($styles));
255    // Update title
256    if (options.title) {
257      var title = $('title', copy);
258      if (title.length === 0) {
259        title = $('<title />');
260        copy.append(title);
261      }
262      title.text(options.title);
263    }
264    // Appedned content
265    copy.append(getjQueryObject(options.append));
266    // Prepended content
267    copy.prepend(getjQueryObject(options.prepend));
268    if (options.manuallyCopyFormValues) {
269      // Manually copy form values into the HTML for printing user-modified input fields
270      // http://stackoverflow.com/a/26707753
271      copy.find('input').each(function() {
272        var $field = $(this);
273        if ($field.is('[type=\'radio\']') || $field.is('[type=\'checkbox\']')) {
274          if ($field.prop('checked')) {
275            $field.attr('checked', 'checked');
276          }
277        } else {
278          $field.attr('value', $field.val());
279        }
280      });
281      copy.find('select').each(function() {
282        var $field = $(this);
283        $field.find(':selected').attr('selected', 'selected');
284      });
285      copy.find('textarea').each(function() {
286        // Fix for https://github.com/DoersGuild/jQuery.print/issues/18#issuecomment-96451589
287        var $field = $(this);
288        $field.text($field.val());
289      });
290    }
291    // Get the HTML markup string
292    var content = copy.html();
293    // Notify with generated markup & cloned elements - useful for logging, etc
294    try {
295      options.deferred.notify('generated_markup', content, copy);
296    } catch (err) {
297      console.warn('Error notifying deferred', err);
298    }
299    // Destroy the copy
300    copy.remove();
301    if (options.iframe) {
302      // Use an iframe for printing
303      try {
304        printContentInIFrame(content, options);
305      } catch (e) {
306        // Use the pop-up method if iframe fails for some reason
307        console.error('Failed to print from iframe', e.stack, e.message);
308        printContentInNewWindow(content, options);
309      }
310    } else {
311      // Use a new window for printing
312      printContentInNewWindow(content, options);
313    }
314    return this;
315  };
316})(jQuery);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.