Print external page without open it - javascript

I want print a page without open it on all major browsers. (Safari, IE, firefox, Chrome and Opera)
I tried that but doesn't work on firefox (Error : Permission denied to access property 'print') :
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
<link rel="alternate" media="print" href="print.php">
<script type="text/javascript">
function impression() {
window.frames[0].focus();
window.frames[0].print();
}
</script>
</head>
<body>
<iframe height="0px" src="print.php" id="fileToPrint" style="visibility: hidden"></iframe>
Imprimer
</body>
</html>
This code works on Chrome.
I want one thing like that for all browsers to mention but I don't know how.
Is there another way to do that?

Create an iframe, hide it, and then call the proper print functions. The execCommand should work for all versions of IE.
Mind you: $.browser won't work for newer versions of jQuery and should be avoided. Use your preferred way of detecting features.
var ifr = createIframe();
ifr.hide();
if ($.browser.msie) {
ifr.contentWindow.document.execCommand('print', false, null);
} else {
ifr.contentWindow.focus();
ifr.contentWindow.print();
}
This was developed for IE, FF and Chrome. I have no idea how well this will work for Safari and Opera, but it might give you some ideas.
Edit: as adeneo correctly pointed out, $.browser is deprecated and should be avoided. I updated my statement. I'll leave my code untouched, as it still expresses the correct intent.

You can try this code, but it's Javascript ;
<script language="JavaScript">
var gAutoPrint = true; // Tells whether to automatically call the print function
function printSpecial()
{
if (document.getElementById != null)
{
var html = '<HTML>\n<HEAD>\n';
if (document.getElementsByTagName != null)
{
var headTags = document.getElementsByTagName("head");
if (headTags.length > 0)
html += headTags[0].innerHTML;
}
html += '\n</HE>\n<BODY>\n';
var printReadyElem = document.getElementById("printReady");
if (printReadyElem != null)
{
html += printReadyElem.innerHTML;
}
else
{
alert("Could not find the printReady function");
return;
}
html += '\n</BO>\n</HT>';
var printWin = window.open("","printSpecial");
printWin.document.open();
printWin.document.write(html);
printWin.document.close();
if (gAutoPrint)
printWin.print();
}
else
{
alert("The print ready feature is only available if you are using an browser. Please update your browswer.");
}
}
</script>

Related

How to access an iframe from chrome extension?

How can I get my extension to work on all frames like adblock does?
I tried adding "all_frames" : true to my manifest file but it didn't work.
I tried to use this code to get the text with specific ids:
var theId = "starts with something";
var myArray = [];
$('[id^="theId"]').each(function(i, obj) {
myArray.push($(this).text());
});
$.unique(myArray);
console.log(myArray);
but it says my array is empty. When I inspect element on the page, I see a "top" layer, and a "target content" layer. The code only works when I execute it in the console on the "target content" layer. Can I use this code in a content script, or do I need to use background.js somehow?
Continued from SO44122853
I see you figured out that the content was loaded in an iframe. So I have a working demo here PLUNKER, the snippet is here just in case the plunker goes down.
Details are commented in PLUNKER
Demo
Not functional due to the need to run 2 separate pages
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<style></style>
</head>
<body>
<!--iframe is same as the one on the site, with the exception
of the src-->
<iframe id="ptifrmtgtframe" name="TargetContent" title="Main Content" frameborder="0" scrolling="auto" width='90%' src="tables.html"></iframe>
<!--The data is displayed as a one string-->
<output id='display'></output>
<script>
// Reference the iframe
var iFID = document.getElementById("ptifrmtgtframe");
// Register the load event on iframe
iFID.onload = function(e) {
// Callback is extractText function
return extractText('#ptifrmtgtframe', '#display', '.PSLONGEDITBOX');
}
/* Pass iframe and display as a single selector
|| Pass targets as a multiple selector
*/
function extractText(iframe, display, targets) {
var iArray = [];
var iFrame = document.querySelector(iframe);
var iView = document.querySelector(display);
var iNode = "";
/* .contentWindow is property that refers to content
|| that is in an iframe. This is the heart of the
|| demo.
*/
var iContent = iFrame.contentDocument || iFrame.contentWindow.document;
var iTarget = iContent.querySelectorAll(targets);
/* .map() will call a function on each element
|| and return a new array as well.
*/
Array.from(iTarget).map(function(node, idx) {
iNode = node.textContent;
iView.textContent += iNode;
iArray.push(iNode);
return iArray;
});
console.log(iArray);
}
</script>
</body>
I think your script may be executing before the DOM loads, try putting your function inside:
document.addEventListener('DOMContentLoaded', function() {
});
EDIT
That event seems to do nothing in content scripts, I think that is because they are already loading after DOM is loaded, and never fires.
However this seems to fire but not sure why:
$(function(){
//something
});
This needs jQuery injected aswell

Javascript redirect infinite loop

Chrome is not redirecting to an intranet site. The body onload method is looping infinitely. If I change the target to an external website such as google.com, the redirection works. Can someone give pointers to find why is there an infinite loop for my intranet site?
Below is my HTML
<!DOCTYPE HTML>
<script type="text/javascript" src="openBrowser.js"></script>
<script type="text/javascript">
function openURL(){
var targetURL="http://myintranetsite";
openBrowser(targetURL);
}
</script>
<BODY onLoad="openURL()">
<div id="loadBrowser"><h1>Opening Browser..</h1></div>
</BODY>
</HTML>
my javascript
var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(isChrome)
{
//Changes the URL to destination if the current chrome browser version is 40
if(getChromeVersion()>=40)
{
window.location=targetURL;
}
}
your code must be redirecting for chrome version 40 or higher, you must see that you are not already in the place where you want to go, causing infinite redirection. Here is the code that can work for you
var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(isChrome)
{
//Changes the URL to destination if the current chrome browser version is 40
if(getChromeVersion()>=40 && window.location!==targetURL)
{
window.location=targetURL;
}
}
Check that window.location isn't your intranet page
if (window.location.hostname.indexOf("myintranetsite") > -1) {
openBrowser(targetURL);
}
Alternatively maybe hit the brakes a little later:
if (window.location.toString() != targetURL && getChromeVersion()>=40) {
window.location=targetURL;
}

browser detection in javascript

I need to show a different webpage when i open my website in IE6 and below version.
Need to show fbrowser.html file when my website opens in IE6 and below versions.
Please suggest!!
In head:
<!--[if lte IE 6]>
<meta http-equiv="refresh" content="0; url=fbrowser.html">
<![endif]-->
Sorry, no javascript needed.
You could consider using http://api.jquery.com/jQuery.browser/
According to this answer, you can try somethiing like the following:
<script type="text/javascript">
// <![CDATA[
var BrowserCheck = Class.create({
initialize: function () {
var userAgent = navigator.userAgent.toLowerCase();
this.version = (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1];
this.safari = /webkit/.test(userAgent) && !/chrome/.test(userAgent);
this.opera = /opera/.test(userAgent);
this.msie = /msie/.test(userAgent) && !/opera/.test(userAgent);
this.mozilla = /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent);
this.chrome = /chrome/.test(userAgent);
}
});
// ]]>
</script>

cloneNode in internet explorer

While executing the following code IE throws the error -- Object doesn't support this property or method -- referring to the cloneNode() method. 'i' is the loop counter, source and dest are both HTML select elements.
dest.options[dest.options.length] = source.options[i].cloneNode( true );
FF and Chrome behave as expected. Any ideas on how to get IE to execute cloneNode()? The IE 8 debugger shows source.options[i] does have a cloneNode() method.
Thanks.
IE requires the
new Option()
construct.
document.createElement( 'option' );
or
cloneNode()
will fail. Of course, all options work as expected in a proper web browser.
Actually, cloneNode isn't throwing any error. Break your code down into smaller chunks to properly identify the source of the error:
var origOpt = source.options[i];
var clonedOpt = origOpt.cloneNode( true ); // no error here
var destOptLength = dest.options.length;
dest.options[destOptLength] = clonedOpt; // error!
dest.options.add(clonedOpt); // this errors too!
dest.appendChild(clonedOpt); // but this works!
Or, putting it back the way you had it, all on one line:
dest.appendChild(source.options[i].cloneNode( true ));
I've found this post useful: IE’s cloneNode doesn’t actually clone!
<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Untitled Document</title>
<style>
p, select,option{font-size:20px;max-width:640px}
</style>
<script>
function testSelect(n, where){
var pa= document.getElementsByName('testselect')[0];
if(!pa){
pa= document.createElement('select');
where.appendChild(pa);
pa.name= 'testselect';
pa.size= '1';
}
while(pa.options.length<n){
var i= pa.options.length;
var oi= document.createElement('option');
pa.appendChild(oi);
oi.value= 100*(i+1)+'';
oi.text= oi.value;
}
pa.selectedIndex= 0;
pa.onchange= function(e){
e= window.event? event.srcElement: e.target;
var val= e.options[e.selectedIndex];
alert(val.text);
}
return pa;
}
window.onload= function(){
var pa= testSelect(10, document.getElementsByTagName('h2')[0]);
var ox= pa.options[0];
pa.appendChild(ox.cloneNode(true))
}
</script>
</head>
<body>
<h2>Dynamic Select:</h2>
<p>You need to insert the select into the document,
and the option into the select,
before IE grants the options any attributes.
This bit creates a select element and 10 options,
and then clones and appends the first option to the end.
<br>It works in most browsers.
</p>
</body>
</html>

Range Selection and Mozilla

I would like to specify that firefox select a range. I can do this easily with IE, using range.select();. It appears that FFX expects a dom element instead. Am I mistaken, or is there a better way to go about this?
I start by getting the text selection, converting it to a range (I think?) and saving the text selection. This is where I'm getting the range from initially:
// Before modifying selection, save it
var userSelection,selectedText = '';
if(window.getSelection){
userSelection=window.getSelection();
}
else if(document.selection){
userSelection=document.selection.createRange();
}
selectedText=userSelection;
if(userSelection.text){
selectedText=userSelection.text;
}
if(/msie|MSIE/.test(navigator.userAgent) == false){
selectedText=selectedText.toString();
}
origRange = userSelection;
I later change the selection (successfully). I do so by range in IE and by a dom ID in ffx. But after I do that, I want to set back the selection to the original selection.
This works like a charm in IE:
setTimeout(function(){
origRange.select();
},1000);
I would like to do something like this in FFX:
var s = w.getSelection();
setTimeout(function(){
s.removeAllRanges();
s.addRange(origRange);
},1000);
Unfortunately, FFX has not been cooperative and this doesn't work. Any ideas?
The short answer is: IE and other browsers differ in their implementations of selecting text using JavaScript (IE has its proprietary methods). Have a look at Selecting text with JavaScript.
Also, see setSelectionRange at MDC.
EDIT: After making a little test case, the problem becomes clear.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>addRange test</title>
<style>
#trigger { background: lightgreen }
</style>
</head>
<body>
<p id="test">This is some (rather short) text.</p>
<span id="trigger">Trigger testCase().</span>
<script>
var origRange;
var reselectFunc = function () {
var savedRange = origRange;
savedRange.removeAllRanges();
savedRange.addRange(origRange);
};
var testCase = function () {
// Before modifying selection, save it
var userSelection,selectedText = '';
if(window.getSelection){
userSelection=window.getSelection();
}
else if(document.selection){
userSelection=document.selection.createRange();
}
selectedText=userSelection;
if(userSelection.text){
selectedText=userSelection.text;
}
if(/msie|MSIE/.test(navigator.userAgent) === false){
/* you shouldn't do this kind of browser sniffing,
users of Opera and WebKit based browsers
can easily spoof the UA string */
selectedText=selectedText.toString();
}
origRange = userSelection;
window.setTimeout(reselectFunc, 1000);
};
window.onload = function () {
var el = document.getElementById("trigger");
el.onmouseover = testCase;
};
</script>
</body>
</html>
When testing this in Firefox, Chromium and Opera, the debugging tools show that after invoking removeAllRanges in reselectFunc, both savedRange and origRange are reset. Invoking addRange with such an object causes an exception to be thrown in Firefox:
uncaught exception: [Exception...
"Could not convert JavaScript argument
arg 0 [nsISelection.addRange]"
nsresult: "0x80570009
(NS_ERROR_XPC_BAD_CONVERT_JS)"
location: "JS frame ::
file:///home/mk/tests/addrange.html ::
anonymous :: line 19" data: no]
No need to say that in all three browsers no text is selected.
Apparently this in intended behaviour. All variables assigned a (DOM)Selection object are reset after calling removeAllRanges.
Thank you Marcel. You're right, the trick is to clone the range, then remove the specific original range. This way we can revert to the cloned range. Your help led me to the below code, which switches the selection to elsewhere, and then back according to a timeout.
I couldn't have done it without you, and grant you the correct answer for it :D
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>addRange test</title>
<style>
#trigger { background: lightgreen }
</style>
</head>
<body>
<p id="switch">Switch to this text</p>
<p id="test">This is some (rather short) text.</p>
<span id="trigger">Trigger testCase().</span>
<script>
var origRange;
var s = window.getSelection();
var reselectFunc = function () {
s.removeAllRanges();
s.addRange(origRange);
};
var testCase = function () {
// Before modifying selection, save it
var userSelection,selectedText = '';
if(window.getSelection){
userSelection=window.getSelection();
}
else if(document.selection){
userSelection=document.selection.createRange();
}
selectedText=userSelection;
if(userSelection.text){
selectedText=userSelection.text;
}
if(/msie|MSIE/.test(navigator.userAgent) === false){
/* you shouldn't do this kind of browser sniffing,
users of Opera and WebKit based browsers
can easily spoof the UA string */
selectedText=selectedText.toString();
}
origRange = userSelection;
var range = s.getRangeAt(0);
origRange = range.cloneRange();
var sasDom = document.getElementById("switch");
s.removeRange(range);
range.selectNode(sasDom);
s.addRange(range);
window.setTimeout(reselectFunc, 1000);
};
window.onload = function () {
var el = document.getElementById("trigger");
el.onmouseover = testCase;
};
</script>
</body>
</html>

Categories

Resources