below code is in one javascript file
==> test.js:
function test(){ window.open('http://example.com/abc/c4adbeb687f77b48a041d70395803358','','toolbar=yes,statusbar=yes,location=yes,menubar=yes,scrollbars=yes,resizable=no,fullscreen=yes');}
how can i get http://example.com/abc/c4adbeb687f77b48a041d70395803358 from a html file with below structure
==>test.html:
<script type="text/javascript" src="test.js"></script>
<script>
alert(window.open.value);
</script>
If you have control over both the HTML and the JS, you can intercept the window.open function:
<script>
var oldWindowOpen = window.open;
var windowOpenArgs = [];
window.open = function() {
windowOpenArgs = arguments;
oldWindowOpen.call(window, arguments);
};
</script>
<script type="text/javascript" src="test.js"></script>
<script>
window.open = oldWindowOpen;
// do stuf with variable windowOpenArgs
console.log(windowOpenArgs[0]); //the url
</script>
You could get more advanced, by throwing and catching a error to find the stack trace and only record the parameters when the call comes from a specific function, but it all depends on the nature of your scripts:
window.open = function() {
try { throw new Error(); } except(e) {
var stack = e.stack;
if (/test#.*?test.js:/.test(stack)) {
windowOpenArgs = arguments;
}
}
}
However notice that the variable will only be set after test() is executed!
Your question seems a bit unclear.... to me.
I presume you are trying to rip the url that is located in a .js file. In your example you want the url http://example.com/abc/c4adbeb687f77b48a041d70395803358 to be ripped out of test.js.
Well, in your example, you have test.js loaded as its in the script tag as you showed here:
<script type="text/javascript" src="test.js"></script>
Therefore, if you know the name of the function that has the url data. You can simply:
alert(test.toSource());
to see its contents. However, it will need to be parsed. One could write a weird looking RegEx expression for it. But, here is a workaround:
alert("http"+test.toSource().split("http")[1].split("',")[0]);
This is a ROUGH workaround. Parsing heavily depends on how people write code. And, in this example, if they used a " instead of ' then it would not display the url correctly. There could be other issues, a nice RegEx could knock it out cleanly tho.
However, if you dont know the functions name. And you just want to blindly search the whole js file for a url (specific or in general), then I would suggest it best to load it with XMLHttpRequest. I guess there is a HttpRequest you could use as well, never looking into it.
var sUrl = "test.js";
var httpRequest = new XMLHttpRequest();
httpRequest.open("GET",sUrl, true);
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4 && httpRequest.status == 200) { // ok
alert ( "http"+httpRequest.responseText.split("http")[1].split("',")[0] );
} else if ( httpRequest.readyState == 4 && httpRequest.status != 200 ) {
// failed
}
};
httpRequest.send(null);
That mess should show an alert box containing the first appearing http url in a function argument from any URL put into sUrl.
If you want more... then that means more parsing. But you can store it from here to do whatever.
But, once you open a window from javascript, you cannot access this new window's contents from within the opening javascript. Cross Domain violation
(some sort of extension of the Same Origin Policy). You can, however, change where its pointing. And, grab the location its pointed to, which might also be what your asking here.
In that case, if the window is already open you can do this
var w = window.open("http:\\example.com"); // some time before
alert(w.location);
However, if you just opened it. Like above. It might be about:blank, because it hasn't loaded yet. In which case you would have to look for it later.. like:
window.open("http:\\example.com", "MyName");
setTimeout('var w = window.open(,"MyName"); alert(w.location);', 1000);
Here, you have to use the window name parameter for window.open. Then, the second time you call window.open you leave the URL parameter blank and only use the window name parameter to get a reference to an existing open window... instead of opening a new one.
Then, if you want to ubiquitously grab all urls passed into window.open, there is a hijack method. It all just depends on what your asking here... but Kroltan beat me to it! lol! So check his answer for that one.
PT
This question already has answers here:
jquery html() strips out script tags
(5 answers)
Closed 9 years ago.
For example:
Some service provided me with JavaScript code for rendering subscription form:
<script type="text/javascript" src="http://example.com/form.js"></script>
Everything works great!
But I need to get this code from other source (ajax for example) and put it on the page dynamically I just can't do it.
Something like that:
var result = '<script type="text/javascript" src="http://example.com/form.js"></script>';
$('#element').html(result);
Nothing shows up.
Yeah I know I can create script element, then edit src attribute and then append element somewhere, but the problem is that result might be HTML or HTML/CSS or JavaScript (script element).
Thank you :)
If you are just looking to gain access to the .js itself, you can get it with an AJAX request to read the file.
Here is an example using jQuery's ajax function. Non-jQuery AJAX requests are easily done, you'll just need to do a quick Google search for the syntax.
$.ajax('http://example.com/form.js')
.done(function(data) { $('#element).html(data); });
If you need to output, you can treat a JS file just like any other text file.
Upon rereading your request, you might be looking to run the JS then grab whatever output that generates and copy that. If that is indeed the case, then it depends on the script as it could do literally anything, so we'll need more information about what the script does.
Try this:
<script type="text/JavaScript">
function loadFile(url) {
function callback() {
if (req.readyState == 4) { // 4 = Loaded
if (req.status == 200) {
if (req.responseText.replace(/(^\s+|\s+$)/g, '').indexOf("<") == 0) {
eval(req.responseText); // It's a script, probably
} else {
// It's HTML, probably
// Insert req.responseText in some element on your page
}
}
}
};
var req = new XMLHttpRequest();
req.onreadystatechange = callback;
req.open("GET", url, true);
req.send("");
}
</script>
Run the loadFile() function with the script source URL as argument.
I'm having trouble with a synchronous AJAX request.
I am creating a web application where there are many AJAX requests called in sequence which should be returned in strict order. Rather than putting every succeeding request in the readystatechange event handler of the last request, I decided to simply call them synchronously.
However, in the following code, alert() is invoked before adding the response to the DOM.
window.addEventListener("load", main, false);
function main (e) {
// Sending synchronous request
var request = new XMLHttpRequest();
request.open("GET", fileName, false);
request.overrideMimeType("text/xml");
request.send(null);
// Receiving response
var response = request.responseXML;
// Changing XML Tree to corresponding XHTML Tree
response = XMLtoXHTML(response);
//Adding response to the body
document.body.appendChild(response);
// Calling alert
alert("Hello World");
}
The response gets in fact successfully added to the DOM, but only after clicking OK on the alert message. When I do a walkthrough using Safari's Script Debugging features, the response does get added to the DOM before calling alert().
Any suggestions?
NB: I left out other requests.
I guess it actually does get added, you just don't see the changes before JS returns control back to the browser, i.e. until alert window is closed. If you cannot do an async request (which I would suggest first), you could at least make dom changes in a separate setTimeouted "thread".
It has indeed been added to the DOM but the page hasn't parsed the new element into view yet. If I had to guess it would be that since alert blocks the current running JS thread webkit tries to perform reflows during this time for efficiency.
Test case:
function foo()
{
var div = document.createElement("div");
div.innerHTML = "hi friends";
div.id = "bar";
document.body.appendChild(div);
alert(document.getElementById("bar").innerHTML);
}
Do you need the element to appear before the alert comes up? Use this in that case
setTimeout(function(){alert("Hello World");}, 1);
Or use a flow control library like Frame.js (or asnyc, flow.js, more):
Frame(function(next)){
document.body.appendChild(response);
next();
});
Frame(function(next)){
alert("Hello World");
next();
});
Frame.init();
I have a page with a dropdown. The onchange event calls a Javascript function (below) that includes an Ajax block that retrieves data and populates a TEXTAREA. On the surface, everything works.
I can select any item in the list with no problems. However, if I select an item that has previously been selected, the Ajax call appears to hang. It looks like maybe some weird caching issue or something. If I close the browser and reload the page, all items work again until I re-select.
I've tested for the readyState and status properties when it's hanging, but I get nothing. Am I missing something?
The page is a client project behind authentication so I can't post a URL, but here's the Ajax code. This is in a PHP page, but there's no PHP script related to this.
function getText( id ) {
var txt = document.getElementById( "MyText" );
txt.disabled = "disabled";
txt.innerText = "";
txt.className = "busy";
var oRequest = zXmlHttp.createRequest();
oRequest.open( "get", "get_text.php?id=" + id, true );
oRequest.send( null );
oRequest.onreadystatechange = function() {
if( oRequest.readyState == 4 ) {
if( oRequest.status == 200 ) {
txt.innerText = oRequest.responseText;
} else {
txt.innerText = oRequest.status + ": " + oRequest.statusText;
}
txt.disabled = "";
txt.className = "";
oRequest = null;
}
}}
Edit: The code block seems a little quirky; it won't let me include the final } unless it's on the same line as the previous.
You're setting the onreadystatechange function after you're sending the request. If it takes a long time (ie if it goes to the server), this will probably work, since there will be a delay before it tries to call the callback.
If the page is cached, though, the browser is probably trying to call onreadystatechange immediately in the send method. Move your assignment to onreadystatechange to before the open/send code.
HI,
The caching is due to the same url thats being called repeatedly. If you change the URl dynamically then this issue can be rsolved. Something like by adding a querystring with the current time with the request ( or any random renerated number ) you can change the url without affecting the result
I would guess that you are running into a caching issue. I have noticed that Internet Explorer is more aggressive at caching ajax calls than Firefox is. One way to be sure of what is happening is to use Fiddler2. This application monitors your web traffic, and you would be able to see if the browser is making a request or not, and what cache headers are coming back on the responses that you do get.
You can download fiddler2 from http://www.fiddlertool.com/fiddler/
I have a system where I send an Ajax command, which returns a script block with a function in it. After this data is correctly inserted in the DIV, I want to be able to call this function to perform the required actions.
Is this possible?
I think to correctly interpret your question under this form: "OK, I'm already done with all the Ajax stuff; I just wish to know if the JavaScript function my Ajax callback inserted into the DIV is callable at any time from that moment on, that is, I do not want to call it contextually to the callback return".
OK, if you mean something like this the answer is yes, you can invoke your new code by that moment at any time during the page persistence within the browser, under the following conditions:
1) Your JavaScript code returned by Ajax callback must be syntactically OK;
2) Even if your function declaration is inserted into a <script> block within an existing <div> element, the browser won't know the new function exists, as the declaration code has never been executed. So, you must eval() your declaration code returned by the Ajax callback, in order to effectively declare your new function and have it available during the whole page lifetime.
Even if quite dummy, this code explains the idea:
<html>
<body>
<div id="div1">
</div>
<div id="div2">
<input type="button" value="Go!" onclick="go()" />
</div>
<script type="text/javascript">
var newsc = '<script id="sc1" type="text/javascript">function go() { alert("GO!") }<\/script>';
var e = document.getElementById('div1');
e.innerHTML = newsc;
eval(document.getElementById('sc1').innerHTML);
</script>
</body>
</html>
I didn't use Ajax, but the concept is the same (even if the example I chose sure isn't much smart :-)
Generally speaking, I do not question your solution design, i.e. whether it is more or less appropriate to externalize + generalize the function in a separate .js file and the like, but please take note that such a solution could raise further problems, especially if your Ajax invocations should repeat, i.e. if the context of the same function should change or in case the declared function persistence should be concerned, so maybe you should seriously consider to change your design to one of the suggested examples in this thread.
Finally, if I misunderstood your question, and you're talking about contextual invocation of the function when your Ajax callback returns, then my feeling is to suggest the Prototype approach described by krosenvold, as it is cross-browser, tested and fully functional, and this can give you a better roadmap for future implementations.
Note: eval() can be easily misused, let say that the request is intercepted by a third party and sends you not trusted code. Then with eval() you would be running this not trusted code. Refer here for the dangers of eval().
Inside the returned HTML/Ajax/JavaScript file, you will have a JavaScript tag. Give it an ID, like runscript. It's uncommon to add an id to these tags, but it's needed to reference it specifically.
<script type="text/javascript" id="runscript">
alert("running from main");
</script>
In the main window, then call the eval function by evaluating only that NEW block of JavaScript code (in this case, it's called runscript):
eval(document.getElementById("runscript").innerHTML);
And it works, at least in Internet Explorer 9 and Google Chrome.
It is fully possible, and there are even some fairly legitimate use cases for this. Using the Prototype framework it's done as follows.
new Ajax.Updater('items', '/items.url', {
parameters: { evalJS: true}
});
See documentation of the Ajax updater. The options are in the common options set. As usual, there are some caveats about where "this" points to, so read the fine print.
The JavaScript code will be evaluated upon load. If the content contains function myFunc(),
you could really just say myFunc() afterwards. Maybe as follows.
if (window["myFunc"])
myFunc()
This checks if the function exists. Maybe someone has a better cross-browser way of doing that which works in Internet Explorer 6.
That seems a rather weird design for your code - it generally makes more sense to have your functions called directly from a .js file, and then only retrieve data with the Ajax call.
However, I believe it should work by calling eval() on the response - provided it is syntactically correct JavaScript code.
With jQuery I would do it using getScript
Just remember if you create a function the way below through ajax...
function foo()
{
console.log('foo');
}
...and execute it via eval, you'll probably get a context problem.
Take this as your callback function:
function callback(result)
{
responseDiv = document.getElementById('responseDiv');
responseDiv.innerHTML = result;
scripts = responseDiv.getElementsByTagName('script');
eval(scripts[0]);
}
You'll be declaring a function inside a function, so this new function will be accessible only on that scope.
If you want to create a global function in this scenario, you could declare it this way:
window.foo = function ()
{
console.log('foo');
};
But, I also think you shouldn't be doing this...
Sorry for any mistake here...
I would like to add that there's an eval function in jQuery allowing you to eval the code globally which should get you rid of any contextual problems. The function is called globalEval() and it worked great for my purposes. Its documentation can be found here.
This is the example code provided by the jQuery API documentation:
function test()
{
jQuery.globalEval("var newVar = true;")
}
test();
// newVar === true
This function is extremely useful when it comes to loading external scripts dynamically which you apparently were trying to do.
A checklist for doing such a thing:
the returned Ajax response is eval(ed).
the functions are declared in form func_name = function() {...}
Better still, use frameworks which handles it like in Prototype. You have Ajax.updater.
PHP side code
Name of file class.sendCode.php
<?php
class sendCode{
function __construct($dateini,$datefin) {
echo $this->printCode($dateini,$datefin);
}
function printCode($dateini,$datefin){
$code =" alert ('code Coming from AJAX {$this->dateini} and {$this->datefin}');";
//Insert all the code you want to execute,
//only javascript or Jquery code , dont incluce <script> tags
return $code ;
}
}
new sendCode($_POST['dateini'],$_POST['datefin']);
Now from your Html page you must trigger the ajax function to send the data.
.... <script src="http://code.jquery.com/jquery-1.9.1.js"></script> ....
Date begin: <input type="text" id="startdate"><br>
Date end : <input type="text" id="enddate"><br>
<input type="button" value="validate'" onclick="triggerAjax()"/>
Now at our local script.js we will define the ajax
function triggerAjax() {
$.ajax({
type: "POST",
url: 'class.sendCode.php',
dataType: "HTML",
data : {
dateini : $('#startdate').val(),
datefin : $('#enddate').val()},
success: function(data){
$.globalEval(data);
// here is where the magic is made by executing the data that comes from
// the php class. That is our javascript code to be executed
}
});
}
This code work as well, instead eval the html i'm going to append the script to the head
function RunJS(objID) {
//alert(http_request.responseText);
var c="";
var ob = document.getElementById(objID).getElementsByTagName("script");
for (var i=0; i < ob.length - 1; i++) {
if (ob[i + 1].text != null)
c+=ob[i + 1].text;
}
var s = document.createElement("script");
s.type = "text/javascript";
s.text = c;
document.getElementsByTagName("head")[0].appendChild(s);
}
My usual ajax calling function:
function xhr_new(targetId, url, busyMsg, finishCB)
{
var xhr;
if(busyMsg !== undefined)
document.getElementById(targetId).innerHTML = busyMsg;
try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); }
catch(e)
{
try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
catch(e2)
{
try { xhr = new XMLHttpRequest(); }
catch(e3) { xhr = false; }
}
}
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
{
var target = document.getElementById(targetId)
target.innerHTML = xhr.responseText;
var scriptElements = target.getElementsByTagName("script");
var i;
for(i = 0; i < scriptElements.length; i++)
eval(scriptElements[i].innerHTML);
if(finishCB !== undefined)
finishCB();
}
else
document.getElementById(targetId).innerHTML = 'Error code: ' + xhr.status;
}
};
xhr.open('GET', url, true);
xhr.send(null);
// return xhr;
}
Some explanation:
targetId is an (usually div) element ID where the ajax call result text will goes.
url is the ajax call url.
busyMsg will be the temporary text in the target element.
finishCB will be called when the ajax transaction finished successfully.
As you see in the xhr.onreadystatechange = function() {...} all of the <script> elements will be collected from the ajax response and will be run one by one. It appears to work very well for me. The two last parameter is optional.
I've tested this and it works. What's the problem? Just put the new function inside your javascript element and then call it. It will work.
This does not sound like a good idea.
You should abstract out the function to include in the rest of your JavaScript code from the data returned by Ajax methods.
For what it's worth, though, (and I don't understand why you're inserting a script block in a div?) even inline script methods written in a script block will be accessible.
I tried all the techniques offered here but finally the way that worked was simply to put the JavaScript function inside the page / file where it is supposed to happen and call it from the response part of the Ajax simply as a function:
...
}, function(data) {
afterOrder();
}
This Worked on the first attempt, so I decided to share.
I solved this today by putting my JavaScript at the bottom of the response HTML.
I had an AJAX request that returned a bunch of HTML that was displayed in an overlay. I needed to attach a click event to a button in the returned response HTML/overlay. On a normal page, I would wrap my JavaScript in a "window.onload" or "$(document).ready" so that it would attach the event handler to the DOM object after the DOM for the new overlay had been rendered, but because this was an AJAX response and not a new page load, that event never happened, the browser never executed my JavaScript, my event handler never got attached to the DOM element, and my new piece of functionality didn't work. Again, I solved my "executing JavaScript in an AJAX response problem" by not using "$(document).ready" in the head of the document, but by placing my JavaScript at the end of the document and having it run after the HTML/DOM had been rendered.
If your AJAX script takes more than a couple milliseconds to run, eval() will always run ahead and evaluate the empty response element before AJAX populates it with the script you're trying to execute.
Rather than mucking around with timing and eval(), here is a pretty simple workaround that should work in most situations and is probably a bit more secure. Using eval() is generally frowned upon because the characters being evaluated as code can easily be manipulated client-side.
Concept
Include your javascript function in the main page. Write it so that any dynamic elements can be accepted as arguments.
In your AJAX file, call the function by using an official DOM event (onclick, onfocus, onblur, onload, etc.) Depending on what other elements are in your response, you can get pretty clever about making it feel seamless. Pass your dynamic elements in as arguments.
When your response element gets populated and the event takes place, the function runs.
Example
In this example, I want to attach a dynamic autocomplete list from the jquery-ui library to an AJAX element AFTER the element has been added to the page. Easy, right?
start.php
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<!-- these libraries are for the autocomplete() function -->
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/ui-lightness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript">
<!--
// this is the ajax call
function editDemoText(ElementID,initialValue) {
try { ajaxRequest = new XMLHttpRequest();
} catch (e) {
try { ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try { ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
return false;
}}}
ajaxRequest.onreadystatechange = function() {
if ( ajaxRequest.readyState == 4 ) {
var ajaxDisplay = document.getElementById('responseDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var queryString = "?ElementID="+ElementID+"&initialValue="+initialValue;
ajaxRequest.open("GET", "ajaxRequest.php"+queryString, true);
ajaxRequest.send(null);
}
// this is the function we wanted to call in AJAX,
// but we put it here instead with an argument (ElementID)
function AttachAutocomplete(ElementID) {
// this list is static, but can easily be pulled in from
// a database using PHP. That would look something like this:
/*
* $list = "";
* $r = mysqli_query($mysqli_link, "SELECT element FROM table");
* while ( $row = mysqli_fetch_array($r) ) {
* $list .= "\".str_replace('"','\"',$row['element'])."\",";
* }
* $list = rtrim($list,",");
*/
var availableIDs = ["Demo1","Demo2","Demo3","Demo4"];
$("#"+ElementID).autocomplete({ source: availableIDs });
}
//-->
</script>
</head>
<body>
<!-- this is where the AJAX response sneaks in after DOM is loaded -->
<!-- we're using an onclick event to trigger the initial AJAX call -->
<div id="responseDiv">I am editable!</div>
</body>
</html>
ajaxRequest.php
<?php
// for this application, onfocus works well because we wouldn't really
// need the autocomplete populated until the user begins typing
echo "<input type=\"text\" id=\"".$_GET['ElementID']."\" onfocus=\"AttachAutocomplete('".$_GET['ElementID']."');\" value=\"".$_GET['initialValue']."\" />\n";
?>
I needed to get something to do this, I find that this has worked for a long time for me, just posting this here as one of many solutions, I like to have solutions without jQuery and the following function may help you, you can pass the full html with script tags in and it will parse and execute.
function parseScript(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
// Loop through every script collected and eval it
for(var i=0; i<scripts.length; i++) {
try {
if (scripts[i] != '')
{
try { //IE
execScript(scripts[i]);
}
catch(ex) //Firefox
{
window.eval(scripts[i]);
}
}
}
catch(e) {
// do what you want here when a script fails
if (e instanceof SyntaxError) console.log (e.message+' - '+scripts[i]);
}
}
// Return the cleaned source
return source;
}
Federico Zancan's answer is correct but you don't have to give your script an ID and eval all your script. Just eval your function name and it can be called.
To achieve this in our project, we wrote a proxy function to call the function returned inside the Ajax response.
function FunctionProxy(functionName){
var func = eval(functionName);
func();
}