Error - Permission denied - jQuery Print Preview? - javascript

When I click "Print" using the jQuery Print Preview Plugin the following error pops up and Firebug:
Error: Permission denied to access property 'name'
if (window.frames[i].name == "print-frame") {
I am not sure exactly what it means or how to correct it.

There is a way around this that will solve this problem and work properly with all major browsers. This solution was found by Derick over on the Github page for jQuery Print Preview.
Here is the solution, around line 44 you will see the following code:
// The frame lives
for (var i=0; i < window.frames.length; i++) {
if (window.frames[i].name == "print-frame") {
var print_frame_ref = window.frames[i].document;
break;
}
}
Replace the above code with this:
print_frame_ref = print_frame[0].contentWindow.document;
issue solved.

Here is the error in Chrome, I expect this makes it clear?
Unsafe JavaScript attempt to access frame with URL http://s7.addthis.com/static/r07/sh090.html#iit=1341762779832&tmr=load%3D1341762779182%26core%3D1341762779520%26main%3D1341762779826%26ifr%3D1341762779833&cb=0&cdn=0&chr=UTF-8&kw=&ab=-&dh=www.ubhape2.com&dr=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F11384440%2Ferror-permission-denied-jquery-print-preview&du=http%3A%2F%2Fwww.ubhape2.com%2Ftest-print.html&dt=TEST%20Page&md=0&cap=tc%3D0%26ab%3D0&inst=1&irt=0&jsl=33&lng=en-US&ogt=&pc=men&pub=ra-4dfb00d56c76d2a5&ssl=0&sid=4ff9acdb1a41cc60&srd=0&srf=0.02&srp=0.2&srl=1&srx=1&ver=300&xck=0&xtr=0&og=&rev=114791&ct=1&xld=1&xd=1 from frame with URL http://www.ubhape2.com/test-print.html. Domains, protocols and ports must match.
Your page is located on ww.ubhape2.com and you are accessing a frame on s7.addthis.com
To fix this problem, change this line
<script type="text/javascript" src="https://s7.addthis.com/js/300/addthis_widget.js#pubid=ra-4dfb00d56c76d2a5"></script>
To point to the copied script on your site.
You will also have to edit that script to only access your own site.
This is an example of XSS or cross site scripting.
My question then turns into can I edit the jQuery Print Preview Script
to prevent the conflict from happening?
No.
The point of the error is that the javascript is running in the context of another party, and you can't "inject" your code into it.
This is enforced by the browser.
If it was not enforced then every user on the internet would have had their machines compromised.
Read up on a google search of XSS to find out more
However,
If you host the javascript (and thus the iframe) on your server than the issue goes away. It is your code (and your iframe) to do with as you wish.

Related

IE error while reading out header with javascript

I'm reading out the header of a webpage through:
var srccat=$("*").contents().filter(function(){return this.nodeType == 8;}).get(0).nodeValue;
Then I'm doing some splits and all, which is all working fine.
(I have to read out the header, because a variable is being 'displayed' as text and there is no other way to get to this info...)
However, the page isn't rendering correctly (because it depends on this) and is throwing an error in the console:
"SCRIPT5: Access is denied."
According to the link to "SCRIPT5" (https://msdn.microsoft.com/query/dev12.query?appId=Dev12IDEF1&l=EN-US&k=k(VS.WebClient.Help.SCRIPT5)), it states: "A script tried to access data from a source other than the host of the current page. The Same Origin Policy followed by Internet Explorer and other browsers allows scripts to access data only from sources with the same scheme, host, and port of the URL of the current page."
I assume this has to do with Backbone. I'm not THAT familiar with it, but I understand that it works as a page within a page, so that in my case it's reading information from the 'parent' page.. and I guess this is not allowed in IE...
The error ONLY occurs in IE(11), not in Firefox or Chrome.
Is there a workaround for this?
I had the same problem with CORS within IE only. I had to use a work around of jQuery's CORS support.
// enables cross origin ressource sharing with IE9
$.support.cors = true;
Is it safe to use $.support.cors = true; in jQuery?
Place this before any other ajax requests are made but after loading jQuery (obviously).

Unable to load script from another server - Content Security Policy issue?

I have been trying to turn a bookmarklet into a small development environment that I can use for testing some javascript and sending commands easily on the fly and updating the code on my server quickly to see the result. This has half way worked using method's I have found in this site and google however it doesn't seem to work very well and sometimes randomly doesn't work. The end goal is to have a bookmarklet that I can click on from any page and it loads a javascript file I have saved on my server. I have created the following two bookmarklets to try and get this working:
Failed Method 1:
javascript:
var s = document.createElement('script');
s.type='text/javascript';
document.body.appendChild(s);
s.src='//smewth.com/test.js';
void(0);
Method 1 in one line bookmarklet form: javascript: var s = document.createElement('script'); s.type='text/javascript'; document.body.appendChild(s); s.src='//smewth.com/test.js'; void(0);
Failed Method 2:
javascript:(
function(){
var imported = document.createElement('script');
imported.type='text/javascript';
imported.src = 'https://smewth.com/test.js';
document.head.appendChild(imported);
})();
Method 2 in one line bookmarklet form: javascript:( function(){ var imported = document.createElement('script'); imported.type='text/javascript'; imported.src = 'https://smewth.com/test.js'; document.head.appendChild(imported); })();
I got method 1 by decomposing the kickass bookmarklet from (http://kickassapp.com/). The actual one I got from their site works fine on my browser no problems. I even did a direct substitution from the URL they were using to load with my URL. The second method I found while searching on this site and this actually worked for a small while and stopped working for some unknown reason (maybe different browsers). I tried appending this script object to the head and the body on each of them with no improved results.
I created the test.js script just for this post and it contains a simple alert box statement:
$$ [/]# cat test.js
alert("hi");
$$ [/]#
NOTE: When I do this with the code embedded within the the bookmarklet itself without appending it to a head/body object then it works fine such as this:
javascript:%20alert("hi");
I did notice that with both of these methods, the code is actually getting injected into the page however I am not seeing the code is ever executed when I click the bookmark. Does anyone know which method is the best or something similar to do this so I can have javascript load through a page which I update on a remote server (reliably)? Maybe I need to attach the to a different object?
Thank you for your help.
-Jeff
UPDATE: I am showing this works while this site is loaded but it doesn't work when your at a site like google.com. Not sure what the difference is or how to accomodate this, google.com has a head and a body object too. I am showing this works in some sites and in some it doesn't.
I figured this out. There were two things occurring which accounts for the intermittent symptom of this issue. The first issue was that the site which was hosting the code was on a self-signed certificate. I began to notice the issue was occurring only when trying to run this from within secure sites. Then in Chrome I saw a error show up in the console. It would be nice if Firefox gave me a error on the console or something as this was the root of the issue. The second thing I had to do was disable OCSP in Firefox as I used a free certificate for testing purposes.
I also had to use method 1 as described above. Firefox and Chrome both did not like the anonymous function call for some reason. From now on I will refer to Chrome to look for errors in the console as Firefox has proven itself not very useful for this.

Stop mobile network proxy from injecting JavaScript

I am using a mobile network based internet connection and the source code is being rewritten when they present the site to the end user.
In the localhost my website looks fine, but when I browse the site from the remote server via the mobile network connection the site looks bad.
Checking the source code I found a piece of JavaScript code is being injected to my pages which is disabling the some CSS that makes site look bad.
I don't want image compression or bandwidth compression instead of my well-designed CSS.
How can I prevent or stop the mobile network provider (Vodafone in this case) from proxy injecting their JavaScript into my source code?
You can use this on your pages. It still compresses and put everything inline but it wont break scripts like jquery because it will escape everything based on W3C Standards
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
On your server you can set the cahce control
"Cache-Control: no-transform"
This will stop ALL modifications and present your site as it is!
Reference docs here
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.5
http://stuartroebuck.blogspot.com/2010/08/official-way-to-bypassing-data.html
Web site exhibits JavaScript error on iPad / iPhone under 3G but not under WiFi
You're certainly not the first. Unfortunately many wireless ISPs have been using this crass and unwelcome approach to compression. It comes from Bytemobile.
What it does is to have a proxy recompress all images you fetch smaller by default (making image quality significantly worse). Then it crudely injects a script into your document that adds an option to load the proper image for each recompressed image. Unfortunately, since the script is a horribly-written 1990s-style JS, it craps all over your namespace, hijacks your event handlers and stands a high chance of messing up your own scripts.
I don't know of a way to stop the injection itself, short of using HTTPS. But what you could do is detect or sabotage the script. For example, if you add a script near the end of the document (between the 1.2.3.4 script inclusion and the inline script trigger) to neuter the onload hook it uses:
<script type="text/javascript">
bmi_SafeAddOnload= function() {};
</script>
then the script wouldn't run, so your events and DOM would be left alone. On the other hand the initial script would still have littered your namespace with junk, and any markup problems it causes will still be there. Also, the user will be stuck with the recompressed images, unable to get the originals.
You could try just letting the user know:
<script type="text/javascript">
if ('bmi_SafeAddOnload' in window) {
var el= document.createElement('div');
el.style.border= 'dashed red 2px';
el.appendChild(document.createTextNode(
'Warning. Your wireless ISP is using an image recompression system '+
'that will make pictures look worse and which may stop this site '+
'from working. There may be a way for you to disable this feature. '+
'Please see your internet provider account settings, or try '+
'using the HTTPS version of this site.'
));
document.body.insertBefore(el, document.body.firstChild);
}
</script>
I'm suprised no one has put this as answer yet. The real solution is:
USE HTTPS!
This is the only way to stop ISPs (or anyone else) from inspecting all your traffic, snooping on your visitors, and modifying your website in flight.
With the advent of Let's Encrypt, getting a certificate is now free and easy. There's really no reason not to use HTTPS in this day and age.
You should also use a combination of redirects and HSTS to keep all of your users on HTTPS.
You provider might have enabled a Bytemobile Unison feature called "clientless personalization". Try accessing the fixed URL http://1.2.3.50/ups/ - if it's configured, you will end up on a page which will offer you to disable all feature you don't like. Including Javascript injection.
Good luck!
Alex.
If you're writing you own websites, adding a header worked for me:
PHP:
Header("Cache-Control: no-transform");
C#:
Response.Cache.SetNoTransforms();
VB.Net:
Response.Cache.SetNoTransforms()
Be sure to use it before any data has been sent to the browser.
I found a trick. Just add:
<!--<![-->
After:
<html>
More information (in German):
http://www.programmierer-forum.de/bmi-speedmanager-und-co-deaktivieren-als-webmaster-t292182.htm#3889392
BMI js it's not only on Vodafone. Verginmedia UK and T-Mobile UK also gives you this extra feature enabled as default and for free. ;-)
In T-mobile it's called "Mobile Broadband Accelerator"
You can Visit:
http://accelerator.t-mobile.co.uk
or
http://1.2.3.50/
to configure it.
In case the above doesn't apply to you or for some reason it's not an option
you could potentially set-up your local proxy (Polipo w/wo Tor)
There is also a Firefox addon called "blocksite"
or as more drastic approach reset tcp connection to 1.2.3.0/24:80 on your firewall.
But unfortunately that wouldn't fix the damage.
Funny enough T-mobile and Verginmedia mobile/broadband support is not aware about this feature! (2011.10.11)
PHP: Header("Cache-Control: no-transform"); Thanks!
I'm glad I found this page.
That Injector script was messing up my php page source code making me think I made an error in my php coding when viewing the page source. Even though the script was blocked with firefox NoScript add on. It was still messing up my code.
Well, after that irritating dilemma, I wanted to get rid of it completely and not just block it with adblock or noscript firefox add ons or just on my php page.
STOP http:// 1.2.3.4 Completely in Firefox: Get the add on: Modify
Headers.
Go to the modify header add on options... now on the Header Tab.
Select Action: Choose ADD.
For Header Name type in: cache-control
For Header Value type in: no-transform
For Comment type in: Block 1.2.3.4
Click add... Then click Start.
The 1.2.3.4 script will not be injected into any more pages! yeah!
I no longer see 1.2.3.4 being blocked by NoScript. cause it's not there. yeah.
But I will still add: PHP: Header("Cache-Control: no-transform"); to my php pages.
If you are getting it on a site that you own or are developing, then you can simply override the function by setting it to null. This is what worked for me just fine.
bmi_SafeAddOnload = null;
As for getting it on other sites you visit, then you could probably open the devtools console and just enter that into there and wipe it out if a page is taking a long time to load. Haven't yet tested that though.
Ok nothing working to me. Then i replace image url every second because when my DOM updates, the problem is here again. Other solution is only use background style auto include in pages. Nothing is clean.
setInterval(function(){ imageUpdate(); }, 1000);
function imageUpdate() {
console.log('######imageUpdate');
var image = document.querySelectorAll("img");
for (var num = 0; num < image.length; num++) {
if (stringBeginWith(image[num].src, "http://1.1.1.1/bmi/***yourfoldershere***")) {
var str=image[num].src;
var res=str.replace("http://1.1.1.1/bmi/***yourfoldershere***", "");
image[num].src = res;
console.log("replace"+str+" by "+res);
/*
other solution is to push img src in data-src and push after dom loading all your data-src in your img src
var data-str=image[num].data-src;
image[num].src = data-str;
*/
}
}
}
function stringEndsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1
}
function stringBeginWith(string, prefix) {
return string.indexOf(prefix, prefix.length-string.length) !== -1
}
An effective solution that I found was to edit your hosts file (/etc/hosts on Unix/Linux type systems, C:\Windows\System32\drivers\etc on Windows) to have:
null 1.2.3.4
Which effectively maps all requests to 1.2.3.4 to null. Tested with my Crazy Johns (owned by Vofafone) mobile broadband. If your provider uses a different IP address for the injected script, just change it to that IP.
Header("Cache-Control: no-transform");
use the above php code in your each php file and you will get rid of 1.2.3.4 code injection.
That's all.
I too was suffering from same problem, now it is rectified. Give a try.
I added to /etc/hosts
1.2.3.4 localhost
Seems to have fixed it.

Permission issues checking if parent site is my parent domain within iframe

I've read several of the questions on this but am still a little confused.
For example: OK, I can't post examples because of hyperlink limitations
Here is my exact situation.
I have a site at mydomain.com
One of the pages has an iframe to another page at sub.mydomain.com
I am trying to prepare an onload script that if the page is not in an iframe or the parent domain of the page containing the iframe is not mydomain.com then redirect to mydomain.com.
After the initial permission issues I realised the problem with sub domains counting as separate domains.
One of the posts above says that "could each use either foo.mydomain.com or just mydomain.com"
So I tried (for testing):
onload="document.domain='mydomain.com';alert(parent.location.href);"
This produced the error (http replaced with lar
Error: Permission denied for <http://sub.mydomain.net> (document.domain=<http://mydomain.net>) to get property Location.href from <http://mydomain.net> (document.domain has not been set).
Source File: http://sub.mydomain.net/?pageID=1&framed=1
Line: 1
Removing the alert produces no errors.
Maybe I am going about this the wrong way since I do not need to interact with the parent just read its domain if there is one.
A nice simple top.domain. For read only there must be a way so that people can prevent their own pages being used within other people's sites.
You can't (easily) do this because of security restrictions.
This answer from #2771397 might point you in the right direction.
OK, while looking at the error console I still had open when I got home a wee lightbulb lit up. I am pretty new to javascript (can you tell ;) but I thought "If it has try/catch"...
well here is a hack at least to get the name of the top domain and an example of how I will use it in my site to show content only if the page is a frame in the correct domain.
Firstly the header will have the following partially PHP generated function:
function getParentDomain()
{
try
{
var wibble=top.location.href;
}
catch(err)
{
if (err.message.indexOf('http://mydomain.com')!=-1)
{
createCookie('IAmAWomble','value')
}
}
}
Basically the value will be something based on the PHP session I think. This will be executed at page load.
If the page is not within the proper site or if javascript is not enabled then the cookie will not be created.
PHP will then attempt to read the correct value from the cookie and show the content or an error message as appropriate.
I do see a slight flaw in this for first visit since page load will run after PHP has generated the content but I'm sure I can work around this somehow. I thought I'd post because this is at least what I was initially asking for and that is a way to read the URL of a parent site if it is in a different domain to the site in the frame.
IIUC you want to use the window.parent attribute: “A reference to the parent of the current window or subframe.”
Assumably, window.parent.document.location.host contains the container page URL domain name.

Firefox Error: Permission Denied to get Window.Document

I have a standard 3-frame layout; "fnav" on the left, "fheader" at the top and "fcontent" below the header. All files are located locally on the hard drive.
This is the JS function that is throwing the error:
function writeHeaderFrame() {
try {
var headerFrame = window.top.frames['fheader'];
var headerTable = document.getElementById('headerTable');
if (headerFrame && headerTable) {
headerFrame.document.body.style.backgroundColor = "Black";
var headerFrameBody = headerFrame.document.documentElement.childNodes[1];
headerFrameBody.innerHTML = headerTable.innerHTML;
} else if (headerTable) {
// there is a headerTable, but no headerFrame
headerTable.style.display = 'inline' // show the headerTable
}
} catch (e) { alert('from header.js, writeHeaderFrame(): ' + e.message); }
}
Clicking on a link in fnav (or initially loading the frameset) loads content into fcontent, then a JS file in fcontent loads the "header" frame... or it is supposed to, anyway. The Javascript runs fine initially, but whenever a link is clicked I get the following error:
Permission Denied To Get Window.document
I am unable to determine why. Any and all suggestions would be appreciated.
First off, please post the code being run when you click those links, and their html.
secondly, did you have a typo there? Window.document should be window.document, should it? (lowercase w)
Edit response to changes in OP question
Without the html it's a little hard to say, but If I were taking a stab in the dark, I'd say this line:
headerFrame.document.body.style.backgroundColor = "Black";
is causing the error. It looks like headerFrame is on a different domain and you don't, for security reasons, have permission to modify the contents of that frame. Of course, some of the following lines will also have the same issue.
Also see http://userscripts.org/topics/25029 and http://www.webdeveloper.com/forum/showthread.php?t=189515 for similar cases.
Edit 2
From Mozilla Development Center
Note: Firefox 3 alters the security for windows' documents so that only the domain from which it was located can access the document. While this may break some existing sites, it's a move made by both Firefox 3 and Internet Explorer 7, and results in improved security.
(see https://developer.mozilla.org/En/DOM/Window.document)
I would guess you're trying to manipulate the window or document from a different origin. HTML5 (and all modern browsers, even IE :D ) enforce (or attempt to enforce) what is called "The Same-Origin Policy". Basically JS from one origin cannot interact with the DOM of a document or window from a different origin.
What is an origin? At a basic level you could substitute domain for origin and almost be right, but the full set of rules are
You must have the same domain
The same port (eg. code on example.com:80 cannot reference the DOM of a page a example.com:8080)
The same protocol (eg. http://example.com is a different origin from https://example.com)
lastly, redirects also matter so (http://example.com -> http://example.com/?redirect=http://evil.com with the server responding with a 3xx redirect to http://evil.com will result in a different origin)
In all liklihood firefox has merely tightened up one area where they did not apply the same origin policy in the past.
Apparently, the user in question updated his installation without changing the following setting to "false", which allows local documents to have access to all other local documents.
pref("security.fileuri.strict_origin_policy", true);
Which explains why I was unable to duplicate the error on my machine.
Many thanks to all for your assistance.
Have you tried installing Firebug and figuring out which line is throwing the error? I'm guessing that since the question is tagged Firefox you are seeing this occur in it.
It'd be most helpful if you could post a template HTML page using this Javascript.
Is the script/frame pages all on the same domain? If not, this is expected. You can't access window.document from another window if they are not on the same domain.

Categories