How can i get a response code of httprequest using java script? - javascript

My need is to get response code the web page using java script. I have to inject this java script in current loading page and get the response code. Is that possible?

function httpGet(){
var url = "test.aspx";
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false);
xmlHttp.send( null );
alert(xmlHttp.responseText);}
Try this one.

Finally i wrote a IE browser extension to return responsecode once the page is loaded.
Written BHO using VC++ refering
http://msdn.microsoft.com/en-us/library/bb250489(v=vs.85).aspx
added listener for events OnDocumentComplete (DISPID_DOCUMENTCOMPLETE),OnNavigateError(DISPID_NAVIGATEERROR) of DIID_DWebBrowserEvents2
now i can able to get pointer of IWebBrowser2 during document complete and navigation error events and also Response code from OnNavigateError->StatusCode->lval.
using IWebBrowser i can append my content to existing webpage after page load and during navigation error.

Related

Load JavaScript file via AJAX without jQuery

I am dynamically loading a widget from another webservice that requires a script to be run immediately after it. The example uses document.write() to do this, but this does not work because it doesn't run until after the document has been closed, which means it overwrites the entire document. I am trying to load it via AJAX using pure JavaScript:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) { // success
eval(this.responseText);
}
};
xhttp.open("GET", "https://d3gxy7nm8y4yjr.cloudfront.net/js/embed.js", true);
xhttp.setRequestHeader('Content-type', 'application/javascript');
xhttp.send();
but I get the following error:
XMLHttpRequest cannot load
https://d3gxy7nm8y4yjr.cloudfront.net/js/embed.js. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://example.com' is therefore not allowed
access.
I was able to make it work using jQuery on my test server with this code:
$.ajax({
dataType: "script",
cache: true,
url: "https://d3gxy7nm8y4yjr.cloudfront.net/js/embed.js"
});
However, I cannot use jQuery on my production server because... well... work politics.
How is jQuery accomplishing this without an error, and how can I do it in pure JavaScript?
Solution
As stated by #shabs, $.ajax adds a script tag to the document.head and then immediately removes it. I checked this by adding a breakpoint and saw it added and removed in Chrome's inspector. It appears to remove the file as soon as the current script completes regardless of what the file is. This works well for immediately invoked scripts, but I don't know how this would work with something like a library.
For a pure JavaScript implementation I used the following code:
var widgetScript = document.createElement("script");
widgetScript.async = true;
widgetScript.src = "https://d3gxy7nm8y4yjr.cloudfront.net/js/embed.js";
document.head.append(widgetScript);
widgetScript.remove();
The resource in question doesn't support CORS.
This works through $.ajax because when you specify dataType: "script", jQuery actually appends a <script> tag to document.head! *
Is there a particular reason you're not just using something like <script type="text/javascript" src="https://d3gxy7nm8y4yjr.cloudfront.net/js/embed.js"></script>?
* (This is news to me! The documentation for $.ajax mentions that "script [...] requests are not subject to the same origin policy restrictions", and the source code confirms this.)

chrome extension Cannot read property 'currentScript' of undefined

I have XHR request defined in my chrome extension which pulls out a javascript file from specific website and execute a function within it. Like this:
//This will return the remote JS file content
function _curl(url) {
var xhr = new XMLHttpRequest();
xhr.open('get', 'https://allow-any-origin.appspot.com/' + url, false);
xhr.send();
return xhr.responseText;
}
//Here I get the JS content and execute it
var rpt = _curl('https://my-page.com/remote.js').match(/\){([^]+)}/)[1];
eval(rpt); //This fails with the error "Cannot read property 'currentScript' of undefined"
The part of JS code in remote file where currentScript is defined is:
...
var Uh=window.document.currentScript&&-1!=window.document.currentScript.src.indexOf("?loadGamesSDK")?"/cast_game_sender.js":"/cast_sender.js",
...
Is this happening because I am trying to execute request in chrome environment? Because, I've also tried executing request within the page by eval contents, which worked. Its just whenever I try to execute same piece of code in my extension, it pops out with this error
I didn't noticed that the script was running in background pages. It always had the window.document property. However, since eval was failing, I tried replacing it with jQuery.globalEval and it worked.
The reason why it worked, I think is that eval was not being executed in global environment, which jQuery.globalEval provided. This answer explain a bit more about this behaviour.
The working code now looks like:
//This will return the remote JS file content
function _curl(url) {
var xhr = new XMLHttpRequest();
xhr.open('get', 'https://allow-any-origin.appspot.com/' + url, false);
xhr.send();
return xhr.responseText;
}
//Here I get the JS content and execute it
var rpt = _curl('https://my-page.com/remote.js').match(/\){([^]+)}/)[1];
jQuery.globalEval(rpt); //This works now

CRM javascript button calls json url and parse a value

I am creating a button in javascript (I can't create it using HTML - system limitation) and I want this button to go to a certain url (REST - getting JSON file). Afterwards, I'd like to display an alert with the value from that file and/or save the value from JSON file on a page where the button is placed. So far, I figured how to call the REST URI. Could anyone help me move forward with that?
<script>
oraclecrmod.onReady(function() {
if(oraclecrmod.ctx.isObject("Account") && oraclecrmod.ctx.isDetailPage()) {
var on_click = function httpGet("https://example.crmondemand.com/OnDemand/user/Rest/027/Accounts")
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "https://example.crmondemand.com/OnDemand/user/Rest/027/Accounts", false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
// Read the "Test Read" button on the main Account TitleBar
var tb = oraclecrmod.getTitleBar("AccountFormTB");
var bt = oraclecrmod.createButton({
id:"TestBtn",
text:"Test Read",
parent:tb
});
bt.on("click",on_click);
}
});
</script>
Is this better? How can I improve it? It still doesn't work.
Once you navigate to another page, your current JavaScript will stop executing. The current Document gets unloaded when you navigate pages.
See the HTML5 spec for more details: http://www.w3.org/TR/html5/browsers.html#the-location-interface

Get content of a custom 404 error page with ajax

I am trying to get the content of a 404 custom page via ajax (Ii need a counter value at this page using Greasemonkey).
Unfortunately jQuery's .fail method of ajax does not give a possibility to actually read the contents of the page like the data value on success.
Is there any workaround? I will also buy vanilla js.
Best rehards
You may do this in Vanilla JS :
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
console.log(httpRequest.responseText);
}
};
pmc.loading.start();
httpRequest.open('GET', url);
httpRequest.send();
Ajax's error callback can be used too :
$.ajax({
url: url,
error: function(httpRequest){
console.log(httpRequest.responseText);
}
});
This being said, I wonder, from your comments, if you're not subject to problems related to same origin policy : you can't read in javascript the content of a page issued from another domain if the site's owner didn't put the right headers.
If that's the case, you can't do anything purely client-side without the consent of the site owner. The easiest would be to add a proxy on your site to serve the page as if it was coming from your site.

How to load a script into a XUL app after initial loading

Greetings,
my xul app needs to load scripts dynamically, for this I derived a function that works in regular html/js apps :
function loadScript(url)
{
var e = document.createElement("script");
e.src = url;
e.type="text/javascript";
document.getElementsByTagName("head")[0].appendChild(e);
}
to something that ought work in XUL :
function loadScript( url)
{
var e = document.createElement("script");
//I can tell from statically loaded scripts that these 2 are set thru attributes
e.setAttribute( 'type' , "application/javascript" ); //type is as per MDC docs
e.setAttribute( 'src' , url );
//XUL apps attach scripts to the window I can tell from firebug, there is no head
document.getElementsByTagName("window")[0].appendChild(e);
}
The script tags get properly added, the attributes look fine,but it does not work at all, no code inside these loaded scripts is executed or even parsed.
Can any one give a hint as to what might be going on ?
T.
Okay,
as usual whenever I post on stack overflow, the answer will come pretty soon thru one last desperate Google search.
This works :
//Check this for how the url should look like :
//https://developer.mozilla.org/en/mozIJSSubScriptLoader
function loadScript( url)
{
var loader = Components.classes["#mozilla.org/moz/jssubscript-loader;1"].getService(Components.interfaces.mozIJSSubScriptLoader);
//The magic happens here
loader.loadSubScript( url );
}
This will only load local files, which is what I need for my app.
I am fairly disappointed by Mozilla, why not do this the same way like html, in a standard way ?
I've tried this, and I think you're right - I can't seem to get XUL to run dynamically appended script tags - perhaps it's a bug.
I'm curious as to why you would want to though - I can't think of any situation where one would need to do this - perhaps whatever you're trying could be achieved another way. Why is it they need to be dynamically loaded?
Off-topic: on the changes you made to the script.
e.setAttribute('src',url); is valid in normal webpages as well, and is actually technically more "correct" than e.src=url; anyway (although longer and not well supported in old browsers).
Types application/javascript or application/ecmascript are supposed to work in normal webpages and are more "correct" than text/javascript, but IE doesn't support them so they're not normally used.
Inside xul environment you are only allowed to use XHR+eval like the following:
function loadScript (url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false); // sync
xhr.send(null);
if (xhr.status && xhr.status != 200)
throw xhr.statusText;
try {
eval(xhr.responseText, window);
} catch (x) {
throw new Error("ERROR in loadScript: Can't load script '" + url+ "'\nError message is:" + x.message);
}
};

Categories

Resources