Cross tab variable in javascript without server interaction - javascript

I am developing a chat system and got a question that I would like to ask you.
I dont think this is possible but since I see similar behaviour in some websites, I would like to know How to access a variable defined/modified in an other tab? I mean I don't want to send it to a server. How to do something like
var myvalue=getValueInAvailableTab(varName);
If it is not possible, how does facebook know if the chat dialog has been closed in another tab? Do they post this event on their server and then retrieve it?
I am sorry I am not stealing behaviours but this is a best example to explain what I want to do.

In most circumstances, the answer to your question is that you cannot access a Javascript variable in another tab. There are other ways to pass data between tabs, however:
You may create a browser extension that has the functionality that you want. Though different browser frameworks have different limitations upon accessing the code of pages that are open.
If the windows are guaranteed to be opened by the same parent window, you may use window.parent or window.opener
If both tabs are from the same origin site, you may have one tab store the value in the cookie, and have the other tab retrieve that value.
These are all ways in which you may accomplish what you need without server interaction. I'm not sure what method Facebook uses, however.

As long as the browser tabs are from the same domain, you can keep track of them by keeping a reference to the return value of window.open(...):
var wins = {};
wins.someTab = window.open(...);
wins.someOtherTab = window.open(...);
Then to access global variables in that tab:
wins.someTab.someVar
And from inside that sub-tab:
opener.wins.someOtherTab.anotherVar

Related

Google Chrome blocked redirect with window.top.location in iframe

I want to redirect my website from iframe to main url, here is my code:
window.setTimeout(function() {
window.top.location = jQuery("link[rel=canonical]").attr("href") + "#ref=shahrekhabar";
return false;
}, 100);
It works on Firefox but Google Chrome blocked this type of redirecttion.
I try with window.top.location.href and window.top.location.replace and window.top.location.assign but no luck.
The reason:
Some spam sites shows my site in iframe and I want to escape from them and I think redirection is good solution.
Edit to answer the TRUE question:
A common issue with stack overflow is that users will often ask how to do something they think solves the problem they are encountering, rather than just asking us how to solve the problem. We always appreciate hearing how you've gone about trying to solve your problem, but it's always best if we know that and what the root problem is. So in your case, given your comment on my answer, the question should have been:
Currently my website is being shown in iframes on sites that I have no control over? I'd like to prevent them from doing this, how can I do so? I'm currently trying to redirect my website from iframe to main url, but it won't work on Chrome. ... Rest of question ...
Given this question, my original answer is useless as:
You still can't and shouldn't be able to alter the URL of the parent window.
You don't own the sites showing your page in the iframe, which means you can't register a listener to handle the postMessage or CustomEvent.
Funny enough, what you're trying to do is the exact reason why chrome doesn't let you do it hahaha. But don't worry there is still a solution.
Introducing CORS!
CORS or Cross Origin Resource Sharing is the name for when a site on one domain accesses resources that aren't on the same domain. Doesn't matter who owns either site, if the two domains are different it's CORS. Now this is good for you because there are such things as CORS policies where you can prevent anyone from even accessing a resource on your domain if they make a CORS request. Keep in mind this will mean you can't display your site within an iframe on another one of your sites unless they're on the same domain, but it sounds like it may be worth it for you.
In case you're curious, unlike what you're trying to do, using CORS policy is very much standard procedure for developers that don't wish for their sites to appear in iframes and is in fact used by famous sites such as facebook, google, and even good ole stackoverflow (I would know, I tried to make a way to view multiple questions at the same time via iframes a while back). I've included an example below that shows this all to be true, alongside an example of a site that doesn't care (editpad.org). In order to implement this on your site check out this link.
<iframe src="https://www.editpad.org/"> </iframe>
<iframe src="https://www.google.com/"> </iframe>
<iframe src="https://www.facebook.com/"> </iframe>
<iframe src="https://stackoverflow.com/posts/53917955"> </iframe>
The old answer:
So you're trying to change the location of the parent window from an iframe? This sounds extremely dangerous and the fact that Firefox doesn't block it worries me. Good job Chrome!
Why wouldn't you want this?
I can think of a few reasons you wouldn't want this, but the biggest is that it's just poor programming. A page should work completely independent of whether or not it is inside an iframe, and even if the page should only be viewed in an iframe it still shouldn't be interacting with the parent window in such a direct way.
Possible issues that could arise if this were allowed on all platforms:
Include an iframe in your ads and as soon as your ad is displayed, redirect the user to your site or worse, redirect them to a mirror of the current site that you're hosting to collect passwords / personal information.
If you can mess with the windows location (arguably the most important and static thing about a web page being viewed) why can't you mess with anything? Can you go into the parent window and adjust the DOM or do a query selection for inputs of type password in order to copy the values? Or what about attaching event listeners to the parent window silently such that you can log any and all key presses.
How can you work around it?
Don't worry too much about the issues I brought up above, as they can all be avoided by following proper standards. In fact, the JavaScript devs envisioned this exact problem which is why you can post messages across windows. Look into this link and go from there, feel free to comment if you have any questions but it should be as simple as posting a message, detecting it on the parent window, and then changing the location as you wish.
If you need to send data from the iframe to the parent window, or your iframe isn't hosted on the same domain, you can instead use CustomEvents (which I prefer even when my iframe is on the same domain) which allow you to attach a data object.
As for why either of these two solutions is better than directly manipulating the parent window, it's all due to the parent window needing to register a listener for the message / custom event. If your page is not inside an iframe it'll simply post a message to itself which it won't be listening for. If your page is inside an iframe on the page it should be on, your parent page should already have registered the proper listeners. And there is no chance for malicious use of these features because again, I have to register a listener and I choose what is done with the event once it's caught.

Can I change the 'window.location' property inside a Bookmarklet and then continue doing things on the new document?

I want know if you can guide to users for a series of steps that imply visit different web pages using actions inside a Bookmarklet. What I want is a kind of Wizard or automated actions cross web pages.
Afraid not. What you're describing would actually be very dangerous. If there were any malicious code in the bookmarklet, it would have access to every site you are logged into, email, amazon etc. Some pseudocode for an attack could look like this:
window.location = "www.gmail.com";
ajax.post("www.gmail.com/deleteAllMail");
window.location = "www.amazon.com";
ajax.post("www.amazon.com/buyReallyExpensiveStuff");
You partially can, if you open the new pages inside an iframe. However, you won't be able to modifying the content of the webpages anymore, but just modifying the url of the iframe, and going through different websites (like a kind of slideshow).
Notice that if you're the owner of the pages, you can use postMessage to interact with them, even if they're in different domains.
Or, you could do a "tunneling" on server side, and inject each team you got the page back with the JS you need.
But probably the cleanest approach if you're not the owner of the pages is just create a simple restartless add-on for the browsers you want to support.

Embedding web controls across sites - using IFrames/Javascript

I'm just looking for clarification on this.
Say I have a small web form, a 'widget' if you will, that gets data, does some client side verification on it or other AJAX-y nonsense, and on clicking a button would direct to another page.
If I wanted this to be an 'embeddable' component, so other people could stick this on their sites, am I limited to basically encapsulating it within an iframe?
And are there any limitations on what I can and can't do in that iframe?
For example, the button that would take you to another page - this would load the content in the iframe? So it would need to exist outwith the iframe?
And finally, if the button the user clicked were to take them to an https page to verify credit-card details, are there any specific security no-nos that would stop this happening?
EDIT: For an example of what I'm on about, think about embedding either googlemaps or multimap on a page.
EDIT EDIT: Okay, I think I get it.
There are Two ways.
One - embed in an IFrame, but this is limited.
Two - create a Javascript API, and ask the consumer to link to this. But this is a lot more complex for both the consumer and the creator.
Have I got that right?
Thanks
Duncan
There's plus points for both methods. I for one, wouldn't use another person's Javascript on my page unless I was absolutely certain I could trust the source. It's not hard to make a malicious script that submits the values of all input boxes on a page. If you don't need access to the contents of the page, then using an iframe would be the best option.
Buttons and links can be "told" to navigate the top or parent frame using the target attribute, like so:
This is a link
<form action="http://some.url/with/a/page" target="_parent"><button type="submit">This is a button</button></form>
In this situation, since you're navigating away from the hosting page, the same-origin-policy wouldn't apply.
In similar situations, widgets are generally iframes placed on your page. iGoogle and Windows Live Gadgets (to my knowlege) are hosted in iframes, and for very good reason - security.
If you are using AJAX I assume you have a server written in C# or Java or some OO language.
It doesn't really matter what language only the syntax will vary.
Either way I would advise against the iFrame methods.
It will open up way way too many holes or problems like Http with Https (or vice-versa) in an iFrame will show a mixed content warning.
So what do you do?
Do a server-side call to the remote site
Parse the response appropriately on the server
Return via AJAX what you need
Display returned content to the user
You know how to do the AJAX just add a server-side call to the remote site.
Java:
URL url = new URL("http://www.WEBSITE.com");
URLConnection conn = url.openConnection();
or
C#:
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://www.WEBSITE.com");
WebResponse res = req.GetResponse();
I think you want to get away from using inline frames if possible. Although they are sometimes useful, they can cause issues with navigation and bookmarking. Generally, if you can do it some other way than an iframe, that is the better method.
Given that you make an AJAX reference, a Javascript pointer would probably be the best bet i.e. embed what you need to do in script tags. Note that this is how Google embed things such as Google Analytics and Google Ads. It also has the benefit of also being pullable from a url hosted by you, thus you can update the code and 'voila' it is active in all the web pages that use this. (Google usually use version numbers as well so they don't switch everyone when they make changes).
Re the credit card scenario, Javascript is bound by the 'same origin policy'. For a clarification, see http://en.wikipedia.org/wiki/Same_origin_policy
Added: Google Maps works in the same way and with some caveats such as a user/site key that explicitly identify who is using the code.
Look into using something like jQuery, create a "plugin" for your component, just one way, and just a thought but if you want to share the component with other folks to use this is one of the things that can be done.

Prevent loss of variables when browser reload button is pressed [duplicate]

This question already has answers here:
Persist variables between page loads
(4 answers)
Closed 7 years ago.
Is it possible to keep my (global) variables when the page is reloaded? If yes, how?
Thanks for any help.
Best regards.
Try this cookie-less javascript function.
It basically store your data in the window.name property which does not clear the value when you reload the page or goes to another site.
You can persist data across page reloads via something like window.localStorage, window.sessionStorage (proprietary Mozilla extension) or database abstraction (window.openDatabase) provided by some of the WebKit -based browsers. See this article on MDC for a nice overview of Storage interfaces and this WebKit article on their database introduction.
In the same style you can store string values in the hash key.
Using the property:
window.location.hash = 'flight/105';
Then when refreshing the page you initialize back your variables.
The JavaScript environment will be reset when the browser leaves your page. However, you could register an onUnload handler to serialise your array to a cookie, then check for this every time the page is loaded and unserialise it if present.
Does your browser have a reset button, or do you mean the reload button?
When the page loads, everything is loaded fresh. There is nothing left from any previous page. The only place to store anything that survives loading a page is in a cookie.
Note that the amount of data that you can put in cookies is limited to a few kilobytes per site. The exact limit varies from browser to browser, but you can't expect to be able to put more than perhaps a kilobyte or two worth of data in cookies.
Are you talking about Cookies? If so you might want to review this open-source module
This will easily allow you to store cookies, that is data, even after a browser reload click. This makes doing it really easy and it is what I use.
var cookie = new HTTP.Cookies();
cookie.write('mydata', 'myvalue', '+1y');
//later on you can get that data EVEN AFTER a reload
var x = cookie.read('mydata');
You probably shouldn't try to make a cookies implementation from scratch though because it is very painful and you have to do a lot of testing across web browsers, such as to make sure Internet Explorer works.

Why do I get an error using moveTo in JavaScript?

I am opening a new window from a button using var myWindow = window.open(...). I then want to move that window to the correct location on the screen. I use myWindow.moveTo(10,10) to do this but I get an Access Denied error.
The window I open contains information from another server to the one I am executing on. When it isn't, the window moves correctly. Is this the limitation and is there a way around it?
I am using IE7. (The work is for an existing Intranet that includes lots of ActiveX so all users use IE7)
You could try to put the information from the other site in an iframe located on the same host that runs the window.open JavaScript. Or maybe even better, get the information server-side and present it directly from your site. Iframes can be trouble.
The window I open contains information from another server to the one I am executing on. When it isn't, the window moves correctly. Is this the limitation and is there a way around it?
Browsers security model have been increasingly restrictive over the last couple of years. What you could do a few years ago, isn't allowed any more. Blame it on advertising companies.

Categories

Resources