run javascript when opening another page - javascript

I'd like to open another web page from javascript (like default navigating, not fullscreen iframe or window.open) and run some javascript code upon loading it.
Steps:
Define a javascript function
Navigate to another page
Browser runs function in new page context
is there any way to achieve this? the only way I remember would be emulating this by loading the page using ajax, and replacing document.body.innerHtml, then running the function, but that would not change location.href, so e.g. the back button or bookmarks wouldn't work. also relative links had to be rewritten at loading, etc...
PS: I know that would be some ugly XSS, but it's needed for example when writing bookmarklets that load a page and fill in a form automatically.

No, you can't do that. That would allow you to do things like steal cookies for session hijacking behind the scenes, so no browsers allow you to do it at all.

While there could be some legitimate use cases, for security reasons you can't do this unless the new page is on the same domain.
What you can do is to write a browser extension if the target browser has extensions support,
Or tell users to open the target page, and use your bookmarklet on that context.

You can do all this stuff if you load the other page from your own server:
Say you want to load http://other.com in your site http://mine.org
You write a tiny serverside script that you can call like this:
http://mine.org/load.php?site1 (with the urls to all the sites you
want to load listed inside load.php or in some database)
but now your site has the security problem: javascript embedded in
http://other.com is run in your sites context.

OK, reserch results:
Impossible methods:
using some persistent function to run on the new page (like I suggested in the question)
using an iframe replacing the whole page (ugly and forbidden by most browsers)
Overkill methods:
write a browser plugin
get the remote page owner to accept some GET argument and do the stuff for you
Remaining method 1, requiring user interaction:
(function(){
if(self.location.href!=targetlocation){
window.alert("Please run this bookmarklet again upon loading the page.");
self.location.href=targetlocation;
}else{
doSomething();
}
return false;
})();
Remaining method 2, doing some nasty proxy stuff:
write some php/etc script to "proxy" the target page
now you can:
use an iframe, because it's not cross-site anymore
rewrite the page server-side before delivering to browser (doing "overkill method: GET argument" by yourself)
Example:
<?php //USAGE: ?uri=http://www.google.com&search[0]=L2dvb2dsZS8K&replace[0]=dGVzdAo=
$page=file_get_contents($_GET["uri"]);
$count = min(count($_GET["search"]),count($_GET["replace"]),100);
for ($i = 0; $i < $count; $i++) {
$page=preg_replace(base64_decode($_GET["search"][$i]),
base64_decode($_GET["replace"][$i]), $page);
}
echo $page;
?>

Related

How to redirect page after "Enable Unsafe Scripts" is enabled?

I have a website that requires "Load Unsafe Scripts" to be enabled to load. What I want is the site to redirect to another after the user enables the "Load Unsafe Scripts" option is enabled. I can work with HTML, and JavaScript. Any help would be appreciated!
As already mentioned, you really should focus on fixing the unsafe script by serving everything (or nothing) from HTTPS.
If you absolutely can't for some reason, and for the sake of exercise: there is no trigger that you can directly react to when this occurs.
Your only real option would be to periodically try to add the script again if it hasn't been already. This wouldn't involve a redirect, but just pulling the script(s) in again.
Something like this:
function loadUnsafe() {
if (!somethingInYourScript) {
const script = document.createElement('script');
script.src = 'https://path.to/my-script.js';
document.appendChild(script);
setTimeout(loadUnsafe, 10000); // wait 10 seconds to try again
}
}
loadUnsafe();
This will try to pull in your script every 10 seconds if somethingInYourScript doesn't exist. Once it does exist, it'll stop.
The somethingInYourScript would be something that the script pulls in (for example, if you were trying to bring in jQuery, you could check if jQuery variable exists because it will once the script is loaded.
You could try to pull in the main file you want (if your site can handle that), or you could try to pull in an unsafe script that would cause a redirect/refresh.
You can load a script from an unsave source which redirect to the other page.
Something like
var locationn = "https://google.com";
window.location = locationn;
But you realy need to make your scripts save...

I can't grab data from opened tab

I wrote this code to grab the content of the page which I opened by javascript but my code doesn't work .
could you tell me whats wrong with my code and it would be better if you introduce me a better way to grab a page content, like what I'm trying to do.
var myWindow = window.open("http://www.w3schools.com/jsref/met_win_open.asp", "MsgWindow", "width=200, height=100");
x = myWindow.document.innerHTML;
alert(x);
There are at least two problems there:
You're trying to get the information before it's available (the window.open call returns immediately, before the page is actually loaded).
You can't access information from other origins because of the Same Origin Policy, unless the other site specifically allows you to.
That second issue pretty much makes what you're trying to do impossible to do purely client-side without help from the other site. Instead, you'd have to have a server that requests the information from the other site, and then sends it to your page. (It doesn't necessarily have to be your server; it's possible to use YQL as a cross-domain proxy and there are probably other similar services out there.)

Force (or ask nicely) to refresh the browser

So I run a site that uses a lot of javascript and ajax. I understand how to make users refresh their browser when the browser loads. But what happens if I need them to refresh their browser after they have loaded the site?
I want to change the ajax that is served to the client to speed up things up, but this is going to cause errors for the users who have not yet refreshed their browser.
The only solution I can come up with is that when a new version of the JavaScript file is required, the site uses a popup that asks the users to force refresh their browsers. (This won't really fix the current version, but would prevent future issues.)
I hate to use a popup for something that I could do automatically. Is there a better way to force updates for the client?
window.location.href = "http://example.com"
replaces the current page with the one pointed to by http://example.com.
You sound like you are having trouble with your JavaScript getting an updated version of the data it loads through Ajax methods, is that correct? For instance, if two Ajax calls try to load 'data.txt', then the second call merely uses the cached version.
You also may be having trouble with loading new versions your script itself.
The way around both of these problems is to add a randomly-generated query string to your script source and your Ajax source.
For example, make one script that loads your main script, like this:
/* loader1.js */
document.write('<script src="mainjavascript.js?.rand=', Math.random(), '"></script>');
And in your HTML, just do
<script src="loader1.js"></script>
The same method works for JavaScript Ajax requests as well. Assuming that "client" is a new XMLHttpRequest() object, and has been properly set up with a readystatechange function and so on, then the you simply append the same query string, like this:
request = client.open('GET', 'data.txt?.rand=' + Math.random(), true);
request.send();
You may be using a library to do your Ajax requests, and so it's even easier then. Just specify the data URL as 'data.txt?.rand=' + Math.random() instead of merely 'data.txt'

load page and execute javascript in a url

Hello wonderful stackoverflow users.
I have a question about url loading.
In many browsers and web viewers, there is the functionality to load a url to a website, but also a url to execute javascript.
Load a website: http://www.google.com
Load a script: javascript:alert("Hello!");
My question is, is there a way to load an http request as well as a javascript.
The answer is most likely no, but I want to confirm because I can't find any resources that describe this.
I was thinking it would be something like:
http://www.google.com&&javascript:alert("Hello!");
but the problem is, of course, this is not correct.
The reason why I am doing this is to provide a url that once it is clicked, it will also execute a certain javascript function. This will be in Android.
I appreciate any response, and understand that the answer may be no.
It all depends on whether you have control of the page being linked to. If you cannot modify the source of the linked page, then the answer is quite simply, no.
But, if it is your page, you can pass arguments in the hash, and then read the hash when the page loads and execute script accordingly.
window.onload = function () {
if (location.hash.indexOf("doSomething") > -1) {
// do something
}
};
You can execute javascript when a page loads using Browser plugins, such as GreaseMonkey for Firefox, or TamperMonkey for Chrome.
https://addons.mozilla.org/en-us/firefox/addon/greasemonkey/
http://tampermonkey.net/index.php?version=3.11&ext=dhdg&updated=true

Checking if a website doesn't permit iframe embed

I am writing a simple lightbox-like plugin for my app, and I need to embed an iframe that is linked to an arbitrary page. The problem is, many web sites (for example, facebook, nytimes, and even stackoverflow) will check to see if is being embedded within a frame and if so, will refresh the page with itself as the parent page. This is a known issue, and I don't think there's anything that can be done about this. However, I would like the ability to know before hand if a site supports embed or not. If it doesn't, I'd like to open the page in a new tab/window instead of using an iframe.
Is there a trick that allows me to check this in javascript?
Maybe there is a server-side script that can check links to see if they permit an iframe embed?
I am developing a browser extension, so there is an opportunity to do something very creative. My extension is loaded on every page, so I'm thinking there's a way to pass a parameter in the iframe url that can be picked up by the extension if it destroys the iframe. Then I can add the domain to a list of sites that don't support iframe embed. This may work since extensions aren't loaded within iframes. I will work on this, but in the meantime....
Clarification:
I am willing to accept that there's no way to "bust" the "frame buster," i.e. I know that I can't display a page in an iframe that doesn't want to be in one. But I'd like for my app to fail gracefully, which means opening the link in a new window if iframe embed is not supported. Ideally, I'd like to check iframe embed support at runtime (javascript), but I can see a potential server-side solution using a proxy like suggested in the comments above. Hopefully, I can build a database of sites that don't allow iframe embed.
Check x-frame-options header by using following code
$url = "http://stackoverflow.com";
$header = get_headers($url, 1);
echo $header["X-Frame-Options"];
If return value DENY, SAMEORIGIN or ALLOW-FROM then you can't use iframe with that url.
Probably pretty late but what you need to do is make a request, likely from your server and look for the x-frame-options header. If it's there at all you can just open a new tab because if it is there is is one of the following: DENY, SAMEORIGIN, ALLOW-FROM. In any of these cases it's likely that you don't have access to open it in an iframe.
This subject has been discussed forever on the web with a particularly interesting (failed) attempt here:
Frame Buster Buster ... buster code needed
The bottom line is that even if you are able to construct a proxy that parses the contents of the page that you want in your iframe and removes the offending code before it is served to the iframe you may still come under "cease and desist" from the site if they get to hear about you doing it.
If you don't want your development to be widely available, you could probably get away with it. If you want your development to become popular, forget about it, and build a less underhand way of dealing with it.
Or develop it for mobile only... ;)
UPDATE: OK following on from your comment here's a bit of taster:
in javascript capture the click on the link
$("a").click(function(e){
preventDefault(e); // make sure the click doesn't happen
// call a server side script using ajax and pass the URL this.href
// return either a true or false; true = iframe breakout
// set the target attribute of the link to "_blank" for new window (if true)
// set the target attribute of the link to "yourframename" for iframe (if false)
// only now load the page in the new window or iframe
});
server side in PHP
$d = file_get_contents($url); // $url is the url your sent from the browser
// now parse $d to find .top .parent etc... in the <head></head> block
// return true or false

Categories

Resources