Referring to object on other page - javascript

I have written a function to remove an iFrame, however the iFrame I want to remove is called in another php-script. I am wondering how i can refer to this script. This is the code for when the iFrame would be in the same script:
function removeFrame(framename,action){
iFrameObject = document.getElementById(framename);
iFrameObject.style.display = action;
}
So i want something like 'otherpage.php.document.getElementbyId(framename)' but I don't really know how to do this..

Before I answer your question, I would highly recommend avoiding situations like this - communication between frames - if at all possible because it becomes messy very quickly.
However, you can accomplished what you're asking for with a small modification to your code. The amended function will when invoked from the iframe or from the parent window itself. Keep in mind, though, that inter-window communication are subject to the same origin policy.
function removeFrame(framename,action){
iFrameObject = window.parent.document.getElementById(framename);
iFrameObject.style.display = action;
}
This change involves pointing to the current window's parent, which in the case of the iframe is the page that embeds it. When the current window has no real parent window, window.parent references the current window (which explains why this function works on the parent page or within an iframe).

Related

Get a value from Iframe into mainPage

I would like to get a value of an input that is on an Iframe.
I would like to get this value when I click on a button that is on the mainPage.
well, I have this piece of code
Javascript on the MainPage:
var targetDiv = document.getElementById('CP_dem');
Html on MainPage:
A tab that when you click on it, it load the Iframe
and a button that call the javascript function
Html on the Iframe:
Zip Code : <input class="textForm" id="CP_dem" type="text" name="CP_dem" maxlength="5" size="5" value="42101">
I would like to get the input value when I click on my MainPageButton.
The javascript code show that "targetDiv" is null.
Can you please help me.
thx
The first thing you have to tell is is:
Is the iframe hosted on the same http host as the parent website? If not, you will run into javascripts same origin protection, read about it at: http://en.wikipedia.org/wiki/Same_origin_policy
In short: You will not be accessible to access the content. But wait! There is a workaround which I will explain after dealing with the second case, where the http host is the same!
So lets talk about that second case. Well then the job is easy...
You just have to access the iframe (probably give the iframe tag an id "example"). Then you can access the window using example.contentWindow.document or example.contentDocument
Whichever is set, depends on the browser. You will have to do some checking in js. Something like
if(document.getElementById('contentWindow.document').contentWindow) {
ifdoc = document.getElementById('contentWindow.document').contentWindow.document
} else {
ifdoc = document.getElementById('contentWindow.document').contentDocument
}
Then you can access the form and element just as you do in javascript, i will not cover that here...
So lets jump to the interesting part of this answer! Lets work around the same origin poliy. This is also called "cross site scripting" (go ahead and google that...)
So basically it comes down to one thing:
There is one property that is accessible from the child as well as from the parent document!
It is the document.location property!
So what can you do?
The child site can modify it and then the parent site can monitor it and react to changes.
Another nice feature is the url fragment (the part which comes after the #). This part does not reload the website, so javascript can modify it happliy and the parent site can poll it in regular intervals and react to it...
Basically this provides a ground for communication for parent and child document which can be worked on. There are beautifully designed librarys for that! The javscript version of "log in with facebook" was based on the same principle!
What this means is that the child document has to cooperate with the parent, therefore it is intentional and both parties basically work together on the job.
So this is OK and it is ok that they work around the same origin policies.
Hope this covers your question in theory and gives you something to work with in praxis!
Have a nice day on SO :)

Inserting <script> into iframe with jQuery

I'm attempting to insert a snippet into an iframe through jQuery with the following:
var snippet = "<script>document.writeln('test')</script>";
jQuery('<iframe />').appendTo('body').append(snippet);
instead of writing "test" in the iframe, it overwrites the parent window.
How can I make it so that the parent window gets the iframe with "test" inserted in it?
You should set the source of new windows and iframes to 'about:blank' if you want control over them. Then reference it by the iframe's ID!
You also want to use iframe.contentDocument || iframe.contentWindow.document
And it might be a good idea to 'open()' the document before you 'write()' to it.
Update: forgot this: If you open the window about:blank, it needs time to load..
So you cannot write to it right away!!
So either set timeout of about 50ms (usually) and then write to the new window/iframe.
OR check if it is loaded (onload), then have it write the source (I prefer this).
If you need to reuse the iframe, set it to about:blank first (again) and wait or check onload again before writing to the frame again. All this is due to xss security.
I also strongly advise to use the traditional event-model (so no addEvent things, they don't work as intended crossbrowser and lead to memoryleaks in IE).
So: create iframe with src set to about:blank, add a onload function that checks a var containing your html-string: if it is empty, else: write it to the iframe and empty the string.
To update the iframe: set content to the var containing the html-string, followed by setting the source of the iframe to about:blank.
Understand the loop?
This baby even works in IE6...
Good luck!!
UPDATE: you did not escape your snippet properly: should be: <script>document.writeln('test')\<\/script>
See: jsfiddle
UPDATE2: argl.. I normally never give up, but since I don't care for jQuery, I'm not going through the manual for jQuery for something something so simple in something as difficult as jQuery (sorry). For modern (crappy) security reasons you need an about:blank. Period.
See this updated fiddle for the 'plain jane' basics at work, then see how to do it in jquery and make a choice: onload or setTimeout. I'm working on my own crossbrowser html-editor and this subject took over a week to figure out.

Changing Window.prototype.open in a way that isn't detectable/reversible

I am looking into ways to extend Firefox pop-up blocking from an extension. One option is replacing window.open() (or rather Window.prototype.open()) in the webpage by a wrapper function. An important requirement is that this manipulation cannot be detected or reverted by the webpage. For example, if I simply do this:
Window.prototype.open = wrapper;
The webpage can easily revert the change by doing:
delete Window.prototype.open;
Instead I can use Object.defineProperty() to set advanced property flags:
Object.defineProperty(Window.prototype, "open", {value: wrapper, configurable: false});
The webpage can no longer revert this change but it can still detect it: delete Window.prototype.open normally changes the value of Window.prototype.open (different instance of the same function it seems), here delete won't have any effect at all. Also, Window.prototype.open = "test";delete Window.prototype.open; will produce inconsistent results (different ones depending on whether writable: false flag is specified for the property).
Is there anything else that I can do to emulate the behavior of the original property (short of using binary XPCOM components which has way too many issues of its own)?
You might try using the nsIWindowWatcher interface to register your own window creator (nsIWindowCreator). That way you can control whether a new window is opened without affecting the window object itself (and thus remaining invisible to web sites).
I'm not sure whether the inability to change the implementation of window.open() without this being detectable is a bug. Perhaps it's just not considered an important requirement for methods like Object.defineProperty. But it might be worth filing a bug to see what others think about making this an option in the future. After all, ad blocking is a major use case.
In the end I had to give up on using JavaScript proxies for the job. Even though with some effort I can create a wrapper for window.open() that behaves exactly like the original (bug 650299 needs to be considered), there doesn't seem to be a proper way to replace the original window.open() function. The changed property will always behave differently from the original one, too bad.
So I decided to go with a different approach as a pop-up blocking solution: listen for content-document-global-created notification and have a look at the subject (the new window) as well as its opener. Windows with a non-null opener are pop-up windows of some kind. One can look at the URLs and decide whether the pop-up should be blocked. To block one would call window.stop() (stops all network activities before any network requests are sent) and window.close(). The latter has to be called asynchronously (with a delay) because it will cause a crash otherwise as the initialization of the window continues. Some notes on this approach:
For pop-ups opening in a new window the window will still show up but disappear immediately. This seems to be unavoidable.
For the web page it looks like its pop-up window opened but was closed immediately - this isn't how the built-in pop-up blocker works, more like an external pop-up blocking application.
New windows always load about:blank first before changing to their actual destination. For same-origin pop-ups the latter won't send a new content-document-global-created notification which is unfortunate.
All in all: not perfect but usable. And it is very simple, nowhere near the amount of code required for JavaScript proxies.
Web browsers intentionally prevent this behavior, it's for maintaing the security of web e.g. when you use iFrame you don't want that iFrame to mess up or hack your page.
But instead of manipulating the window object properties why not to create a wrapper for the window object and override window by the wrapper locally?
Example:
// Copy window object to wraper
var wrapper = {};
for(prop in window) {
wrapper[prop] = window[prop];
}
wrapper.open = function yourNewOpenFunction() {
/// do your custom code here
}
(function fakeScope(window){
window.open(); // this is wrapper.open
}(wrapper));
BTW this affects only the body inside fakeScope() function, and cannot be applied globally.
it striked me this morning: you can use Object.freeze(Window.prototype); !
test have shown, that methods protected with this cannon be deleted, but they can be easily detected.
old answer:
What about ES:Harmony Proxies ?
http://brendaneich.com/2010/11/proxy-inception/
Of course, they are unstable, but they are working in Firefox 4+, and you are not the man, who is afraid of difficulties ;)

Firefox sidebar calling javascript functions in main browser window

I'm trying to put together a quick Firefox sidebar for internal use only.
I'm struggling a bit in understanding how sidebar and main browser window communicate. What I want to do exactly is call existing javascript functions that reside in the main browser window only.
My code looks like this;
ff-sidebar.xul
<checkbox label="Button hover" checked="false" oncommand="add_enhance(this)"/>
ff-sidebar.js
function add_enhance(cb){
if (cb.checked) {
// this bit is wrong I know
window.content.document.NEWSTYLE.buttonHover();
}
}
So the question is, how do I call a function called NEWSTYLE.buttonHover() that lives in the main window?
Theoretically, this should work:
window.content.NEWSTYLE.buttonHover();
window.content points to the browser content window and the variable NEWSTYLE is defined on this window. In reality things are a bit more messy due to security mechanisms - privileged code cannot access objects of unprivileged code directly. Instead you get to access them through XPCNativeWrapper (see https://developer.mozilla.org/en/XPCNativeWrapper). Technical details changed somewhat in Firefox 4 but essentially it is still the same.
The easiest way to do what you want without introducing security issues is changing the location of the content window to a javascript: URL. Like this:
window.content.location.href = "javascript:void NEWSTYLE.buttonHover()";
You won't be able to get the result of this function but it doesn't look like you need it.

How do I write content to another browser window using Javascript?

I've opened a new window with window.open() and I want to use the reference from the window.open() call to then write content to the new window. I've tried copying HTML from the old window to the new window by using myWindow.document.body.innerHTML = oldWindowDiv.innerHTML; but that's doesn't work. Any ideas?
The reference returned by window.open() is to the child window's window object. So you can do anything you would normally do, here's an example:
var myWindow = window.open('...')
myWindow.document.getElementById('foo').style.backgroundColor = 'red'
Bear in mind that this will only work if the parent and child windows have the same domain. Otherwise cross-site scripting security restrictions will stop you.
I think this will do the trick.
function popUp(){
var newWindow = window.open("","Test","width=300,height=300,scrollbars=1,resizable=1")
//read text from textbox placed in parent window
var text = document.form.input.value
var html = "<html><head></head><body>Hello, <b>"+ text +"</b>."
html += "How are you today?</body></html>"
newWindow .document.open()
newWindow .document.write(html)
newWindow .document.close()
}
The form solution that Vijesh mentions is the basic idea behind communicating data between windows. If you're looking for some library code, there's a great jQuery plugin for exactly this: WindowMsg (see link at bottom due to weird Stack Overflow auto-linking bug).
As I described in my answer here: How can I implement the pop out functionality of chat windows in GMail? WindowMsg uses a form in each window and then the window.document.form['foo'] hash for communication. As Dan mentions above, this does only work if the window's share a domain.
Also as mentioned in the other thread, you can use the JSON 2 lib from JSON.org to serialize javascript objects for sending between windows in this manner rather than having to communicate solely using strings.
WindowMsg:
http://www.sfpeter.com/2008/03/13/communication-between-browser-windows-with-jquery-my-new-plugin/
myWindow.document.writeln(documentString)

Categories