1

I'm developing userscript for one webpage (aka browser plugin). I need to update one global Javascript variable (lets call it gVariable (it is an array)) with the one I get with ajax request.

In ajax request I'm requesting for the same page I'm on. But just want to "extract" that one global variable and replace current one with the one downloaded.

This is something I have now (not working).

function LoadNewItemList() {
    $.get(window.location, function (data) {
        var $data = $(data);       
        unsafeWindow.gVariable = data.gVariable; //I'm getting 'undefined'
    });
}

JS test: http://jsfiddle.net/ywVKT/15/

10
  • It seems to me you are reloading the entire current page via AJAX? And then hoping to extract a variable defined in JavaScript within the markup of that page? Or am I misreading things... window.location would have to point to a JSON structure in order to treat data as a navigable object. When you load via AJAX you are just loading the page markup, not a rendered DOM like you would loading a new window... Commented Apr 18, 2014 at 8:30
  • @pebbl Yes. I'm loading whole page. But is there any way to parse scripts and get that variable value? Commented Apr 18, 2014 at 8:41
  • @PratikJoshi How would that help? All code is in my post. Commented Apr 18, 2014 at 8:47
  • plz post it .else you will keep getting comments ,like past half an hour Commented Apr 18, 2014 at 8:48
  • @PratikJoshi jsfiddle.net/ywVKT/14 Commented Apr 18, 2014 at 8:57

2 Answers 2

1

Looking at your fiddle, there are mainly 4 tags. i.e. "title" , "link" , "ul" , "script". That's why you need to use index as 3, since the script tag contains the variable name and value. Try this and it would work.

$('#variableHere').text(data2[3].innerText);

it will return you following o/p: var gVariable = 0; gVariable = 5 Now you can use regex/substring function to extract the vairable name and value..

Sign up to request clarification or add additional context in comments.

Comments

0

I found solution:

unsafeWindow.gVariable = 0;
var $script = $data.filter('script:contains("var gVariable")').first();
eval($script.text());
unsafeWindow.gVariable = gVariable;

2 Comments

Glad you found an answer, but personally I wouldn't like to use that solution myself. From a point of view of optimisation it's just not cricket... you are evaluating the entire returned DOM and script tag.. if that script tag only contains a simple variable then fine, but a RegExp on the markup for something so simple would be safer, more optimal and faster.
Yes. I use regex to only evaluate value for that one variable. But I didn't show it to make this code as simple as possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.