JavaScript window.opener call parent function - javascript

I am trying to call a javascript function defined in a parent from a child window. I have two files like this:
Parent:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function foo () {
alert ("Hello from parent!");
}
function doStuff () {
var w = window.open("testa.html");
}
</script>
</head>
<body>
<input type="button" value="open" onClick="doStuff();" />
</body>
</html>
And child:
<html>
<head>
<title>Test A</title>
<script type="text/javascript">
function get() {
window.opener.foo();
}
</script>
</head>
<body>
<input type="button" value="Call Parent" onClick="get();" />
</body>
</html>
I can not, for the life of me, call the function foo from the child process. I thought this should be possible with the window.opener object, but I can not seem to make this work. Any suggestions?

Ensure you are accessing this via http:// so the Same origin policy passes and you can access opener from the child. It won't work if you're just using file://.

Answering Rahul's question:
Every browser can load pages from server or from local filesystem. To load file from local filesystem you should put to the browser the address like this file://[path], where [path] is the absolute path to the file in filesystem (including drive letter on Windows, see http://blogs.msdn.com/b/ie/archive/2006/12/06/file-uris-in-windows.aspx for details).
To load file from local HTTP server (if you have one) you should put to address something like this http://localhost:[port]/[path], where [port] is the port where your server is running (default is 80) and [path] is the path of the file relative to the server's document root folder. Document root folder depends on the server configuration.
So, as you see, the same local file can be loaded to the browser in two ways. There is however big difference between these two ways. In the first case the browser doesn't use HTTP protocol to load the file and therefore is missing many things necessary for different mechanisms to work properly. For example AJAX doesn't work with local files, as HTTP response status is not 200, etc.
In this particular example the browser security mechanism didn't get the origin information and was preventing from accessing the parent window.

Related

javascript error - Scripts are not found

Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
var path = '/Scripts/';
document.write('<base href="' + path + '"/>');
</script>
</head>
<body>
<h1>WELCOME</h1>
<script src="test.js"></script>
</body>
</html>
test.js
console.log("Message from external script");
output
error.png
Here you can see, first it try to load the script from body tag before it get the actual base href path from script section.
Is there any way to get come out from this error? I mean not to load body script until base href set.
Once the base href set, it executed successfully.
Thanks.
The behavior you're seeing is (somewhat) browser-specific, and is related to your use of document.write to set the base href dynamically.
Chrome and Firefox try to load the page resources before applying the document.write, then updates those urls and tries again after you set the page <base>. Safari appears to not do this; it uses the inserted base href immediately. I have not tested other browsers.
(In all browsers the <base> tag, whether static or dynamic, needs to appear in the document before any links that depend on it.)
Other than the extra network request this seems to be harmless (see below), but you could avoid it by using a static <base> tag instead of dynamically writing one in, or by setting the full path on the <script> tag instead of depending on the <base>.
(re "harmless": I checked the case where a test.js exists both at the root level and inside the "/Scripts" directory. Dynamically inserting the "/Scripts/" base href did not cause both scripts to execute in Chrome: successful network requests for both test.js files were made, but only the code in "/Scripts/" was executed. So the browser makers have handled that edge case already. Good job, browser makers!)
You Can use this code
<script src="./scripts/test.js" type="text/javascript"></script>

how to call REST API from javascript

I have a url which gives json data...
I want to hit that URL from javascript but I am getting this error :
character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature
Code :
function a(){
$.getJSON(url,function(data) { alert(data);});
}
full code :
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" ></meta>
<script language="JavaScript" type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script>
function a(){
$.getJSON(url,function(data) { alert(data);});
}
</script>
</head>
<body>
<input type="text"/>
<input type="submit" value="search" onclick="a()"/>
</body>
</html>
Your code seems correct.
Are you making a fully qualified URL call?
If you are making a fully qualified URL call, make sure of the following.
You are calling the same domain(same server). You can not make a
simple JSON call to another domain.
If you want to use a cross domain call, you'll have to use JSONp
Update:
This is not working since it is a cross domain call.
Work around for this
JavaScript
Create a function
function getMyData(data) {
alert(data);
//Do the magic with your data
}
Server side
On server end wrap your data inside function syntax
getMyData("Enter your data here");
JavaScript
Then create a script tag and add a link to your cross-domain page
<script type="text/javascript"
src="cross ref url">
</script>
For reference: wikipedia
EDIT: Another option is Create a proxy on your domain. ie create a page in your domain which internally calls the cross-domain page and return the same data to your Ajax call.

Cross Domain JavaScript Communication

Here's a situation. My customers would be having their own web pages. On that page they might have an iFrame in which they can show a page located on my server. Outside the iFrame they would have simple buttons, which when clicked should execute javascript functions in iFrame.
So basically the code of customer's web page on customer's domain would be something like this
<input type="button" value="Say Hi" id="TestButton">
<iframe src="myserver.com/some_html_page.htm" width="800" height="550"></iframe>
And code of myserver.com/some_html_page.htm would be
$("#TestButton").click(function(){
alert("Hi");
});
I did my reserach and I am aware of the Browser Security issues, but I want to know is there any way to handle this, may be with json or something ?
As you can already tell (given the parent and child are on different domains), you definitely cannot reach up from the child iFrame into the parent to listen for events.
One way around this is to pass messages between the pages. This will require your clients to include additional javascript in their page as well as the iFrame which points to your server. This is supported in native javascript with postMessage, but including the library #Mark Price suggests will make your life much easier.
So here goes an example:
Clients Page:
...
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.postMessage.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#TestButton").click(function(){
jQuery.postMessage("say_hi", "myserver.com/some_html_page.htm");
});
});
</script>
</head>
<input type="button" value="Say Hi" id="TestButton">
<iframe src="myserver.com/some_html_page.htm"></iframe>
Code on myserver.com/some_html_page.htm:
...
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.postMessage.min.js"></script>
<script type="text/javascript">
// you will need to set this dynamically, perhaps by having your
// clients pass it into the URL of the iFrame,
// e.g. <iframe src="myserver.com/some_html_page.htm?source_url=..
var source_origin = "clients_page.com/index.html";
var messageHandler = function (data) {
// process 'data' to decide what action to take...
alert("Hi");
};
$.receiveMessage(messageHandler, source_origin);
</script>
</head>
Probably it would be nice to bundle the client code up into a single library that they could include, so your clients aren't burdened with writing their own javascript.
As a caveat, I wrote this code off the top of my head and it is likely be rife with typos. I have used this library before to accomplish similar goals, and I hope this answer is a useful jumping off point for you (along with the plugin documentation).
Let me know if I can clarify anything, and best of luck! :)
You could try this jquery plugin from Ben Alman, providing you can have the plugin running on both yours, and your clients servers - see the examples for ways to execute js cross domain :
http://benalman.com/code/projects/jquery-postmessage/docs/files/jquery-ba-postmessage-js.html
Lets consider if you have a function called test() which loads under Iframe, then you can access that test() function as below
document.getElementsByName("name of iframe")[0].contentWindow.functionName()
e.g.
document.getElementsByName("iframe1")[0].contentWindow.test()
One of the common patterns of doing cross-domain requests, is using JSONP.

How am I able to get options which are set in options.html?

I read Google Chrome Extensions Developer's Guide carefully, it told me to save options in localStorage, but how is content_scripts able to get access to these options?
Sample:
I want to write a script for a couple of domains, and this script should share some options on these domains.
content_scripts:
//Runs on several domains
(function(){
var option=getOptions();
//Get options which have been set in options.html
if(option){
doSome();
}
})
option_page:
<html>
<head>
<title>My Test Extension Options</title>
</head>
<body>
option: <input id="option" type="text" /><br />
<input id="save" type="submit" /><br />
<span id="tips">option saved</span>
<script type="text/javascript">
(function(){
var input=document.getElementById('option');
var save=document.getElementById('save');
var tips=document.getElementById('tips');
input.value=localStorage.option||'';
// Here localStorage.option is what I want content_scripts to get.
function hideTips(){
tips.style.visibility='hidden';
}
function saveHandler(){
localStorage.option=input.value||'';
tips.style.visibility='visible';
setTimeout(hideTips,1000);
}
hideTips();
save.addEventListener('click',saveHandler);
})();
</script>
</body>
</html>
I would think you could use the chrome.extensions.* API to create a line of communication to a background page that is running under your extension ID, thus giving you local storage.
I think this is possible because the Content Script docs specify that the chrome.extensions* API's are available to content scripts. But I have never tried this.
You would then just have to send messages from the background page to the content script when a connection is made. You could even send one message with all the settings in a literal object.
Here is an example of creating two way communication I wrote about earlier. You could implement this or create a custom solution but I think this is how you would achieve what you are looking for.

jQuery $.load() functioning on personal webserver, but not production webserver

EDIT: I have discovered that this is a 405 error. So there is something going on with the webserver and handling POST methods.
I am having a strange occurrence. I have identical javascript code on both my test environment and production environment.
The test environment functions, and the production does not. Here is my identical code.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jquerytools.org/1.1.2/jquery.tools.min.js"></script>
<script type="text/javascript" src="./js/jquery.scrollTo-min.js"></script>
</head>
<body>
<div class="content" id="content">
<a id="changeText" href="test.html">Change</a>
</div>
<script>
$(document).ready(function() {
$("#changeText").live('click', function(){
var url = $(this).attr("href");
$("#content").load(url, {var1:Math.random()*99999},function(){
alert(url + " loaded");
});
$.scrollTo("0%", 400);
return false;
});
});
</script>
</body>
</html>
Both environments report that
alert(url + " loaded");
is happening. But only my test environment actually displays the change.
The production webserver has "test.html" available in the correct location.
Are you sure the scrollTo script is being included on the production server ( or am I misinterpreting what you mean by change ) ? Perhaps try a root relative path instead of './js'? I would check Firebug's script tab to ensure it is being included.
405 errors mean that the URL you're sending to isn't expecting you to send the data in that manner. For example, if you're sending a POST request to a URL that's only designed to handle a GET request, you'll get this error.
My guess is whatever server you're running on is set up to not allow POST data to be sent to a page with a .html extension, causing the error you're seeing. Try changing the extension to a .php, .aspx, etc, and see if that helps.

Categories

Resources