chrome extension Cannot read property 'currentScript' of undefined - javascript

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

Related

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

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.

Uncaught TypeError: Cannot read property 'responseText' of undefined

I got a register page on my website, The problem is that i started to get this errors:
Uncaught TypeError: Cannot read property 'responseText' of undefined
Refused to set unsafe header "Content-length" register.php:1
Refused to set unsafe header "Connection"
Even without the last 2 errors (if i dont set the connection,content-length headers) i will get the first error.
For my ajax functionality i am using this function:
function AjaxLoad(xhr, url, cfunc, syn, method, headers, params)
{
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = cfunc; // This line take place on true/false
xhr.open(method, url, syn);
$.each(headers ,function(index, value){
xhr.setRequestHeader(index, value);
});
xhr.send(params);
}
At my js code i am calling the function like that:
var headersObject = {"Content-type" : "application/x-www-form-urlencoded", "Content-length" : userCap.val().length, "Connection" : "close" };
AjaxLoad(
xhr,
"../php/Ajax/captchaValidator.php",
getResponse,
false,
"POST",
headersObject,
userCap.attr("name") + "=" + encodeURIComponent(userCap.val())
);
AjaxLoad arguments explanation:
xhr object
location
onreadystatechange handler
Synchronous(its not working even if i will pass true)
method
headers
key=value pair(I did test it so it get the right value)
This is the getResponse function:
function getResponse(){
var strongEl = capCon.next();
if(xhr.responseText == "0"){
if(strongEl.prop("tagName") == "STRONG"){
strongEl.getReplace('<strong id="sE">קוד שגוי</strong>');
}else{
capCon.after('<strong id="sE">קוד שגוי</strong>').next();
}
bToSubmit = false;
}else{
if(strongEl.prop("tagName") == "STRONG"){
strongEl.remove();
}
}
}
I test the network to see if the file captchaValidator.php is even get to the browser and i get status 200 everything seems ok.
I did test for right values, The code did worked before i dont know what changed, But this is the link to my website registration page Link, If you press send, You can see (in chrome browser at the network tab) that all is ok, But i get the errors i mentioned at the console tab, If some one can please take a look i will be very thankful.
As the error says, the xhr variable is undefined. With a quick glance at the getResponse function you can see that it's probably not in scope. The one that is a parameter to AjaxLoad is local to that function (btw, having it as a parameter seems pretty useless as the first thing you do is assigning to it), and the one which your passing as an argument in your invocation is probably undefined or from a different scope.
Instead, you can access the current XMLHttpRequest object from the event handler with the this keyword. Change your code to
if (this.responseText == "0"){
If you're trying to use ajax and have jQuery, use $.ajax and friends:
$.post(
"../php/Ajax/captchaValidator.php",
userCap.attr("name") + "=" + encodeURIComponent(userCap.val()),
function(responseData) {
//...
}
)
Your code doesn't work because the variable xhr is not in the scope of getResponse. You can use this inside the event handler instead of xhr to refer to the XHR object.

XML accessible from URL line but not from script

When I type a certain URL in FF, I get the XML returned displayed on the screen, so the web service is apparently working. However, when I try to access it from a local HTML document running JS, I get unexpected behavior. The returned code is "200 OK" but there's no text (or rather it's an empty string) nor xml (it's null) in the response sections according to FireBug.
This is how I make the call.
var httpObject = new XMLHttpRequest();
httpObject.open("GET", targetUrl, true);
httpObject.onreadystatechange = function () {
if (httpObject.readyState == 4) {
var responseText = httpObject.responseText;
var responseXml = httpObject.responseXML;
}
}
httpObject.send(null);
Why does it happen and how do I tackle it?
That may be an HTTP header problem (e.g. missing Accept header); observe the headers sent by FF (you can use Firebug for that) and try to replicate them in your script (setRequestHeader).
Otherwise, that may be a "same origin policy" problem.

XMLHTTPrequest request not working

I tried the following code to send request to jsp page on a click of button. I checked on Httpfox but no request is going. I just used the whole of this code in the body of the html code. Am I doing some silly mistake. Kindly suggest..
<button type="button" onClick="handleButtonClick();">Click Me!</button>
<script type="text/javascript">
function handleButtonClick()
{
// Declare the variables we'll be using
var xmlHttp, handleRequestStateChange;
// Define the function to be called when our AJAX request's state changes:
handleRequestStateChange = function()
{
// Check to see if this state change was "request complete", and
// there was no server error (404 Not Found, 500 Server Error, etc)
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var substring=xmlHttp.responseText;
// Do something with the text here
alert(substring);
}
}
xmlhttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://csce:8080/test/index.jsp?id=c6c684d9cc99476a7e7e853d77540ceb", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
</script>
Well, in JavaScript, variables are case-sensitive. You have xmlHttp and xmlhttp; those should be the same.
You've also got <pre><code> at the beginning of your <script> block, which is a JavaScript syntax error.
Since no request is being made, I am not convinced you can actually make requests to "http://csce:8080" as FireFox may not see that URL as being on the same subdomain (You cannot make Ajax requests for resources not on the same domain as the requestor).
Suppose you made the URL relative. Is a request even generated then? If so, that is likely your problem.
Quote: xmlhttp = new XMLHttpRequest();
Two things. First, you might want to use a more robust method of getting an XMLHttpRequest object. Second, javascript is case-sensitive; xmlhttp != xmlHttp
xmlHttp = (function (x,y,i) {
if (x) return new x();
for (i=0; i<y.length; y++) try {
return new ActiveXObject(y[i]);
} catch (e) {}
})(
window.XMLHttpRequest,
['Msxml2.XMLHTTP','Microsoft.XMLHTTP']
);
Quote: http://csce:8080/test/ind...
Keep in mind that cross-domain xmlhttp is verboten. Unless you're serving from csce:8080, that ain't gonna work.

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