5

I have the following function defined in my site. It works for some people, not for others. The exception occurs on the last line in the method, where the concatenation is. I believe that because url's question mark character designating the query string is being looked as a ternary operator.

Is there something here that I'm not seeing, or is there a better way to build this string?

The url variable has a value of : "mywebpage.aspx?AccountNumber=123456"

function popUp(url) {
    var myleft = (screen.width) ? (screen.width - 750) / 2 : 100;
    var   mytop = (screen.height) ? (screen.height - 300) / 2 : 100;
    var id = new Date().getTime();

    eval("page" + id + " = window.open(" + url + ", '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=900,height=325, top='" + mytop + "',left='" + myleft +");");
}
mhu
  • 17,720
  • 10
  • 62
  • 93
Jeff Reddy
  • 5,551
  • 9
  • 55
  • 88
  • 3
    You need to wrap the `url` in `'` so javascript knows it's a string. – Liam Apr 15 '15 at 15:37
  • 7
    You don't need to do this with `eval()`, and as in any case involving `eval()` that means you *shouldn't* do it with `eval()`. – Pointy Apr 15 '15 at 15:37
  • Off topic: http://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil – isherwood Apr 15 '15 at 15:37

3 Answers3

11

You'll eliminate the "quotes within quotes" problem by avoiding eval():

window["page" + id] =
    window.open(url, id, 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=900,height=325, top=' + mytop + ',left=' + myleft);

You should also make sure you use an "id" value that serves as a valid identifier (starts with a non-digit character, specifically) or else Internet Explorer will throw an error.

Pointy
  • 405,095
  • 59
  • 585
  • 614
3

Have you tried to put single quotes before and after closing and opening double quotes around url variable? Somthing like:

 ..." = window.open('" + url + "',... 
Gardax
  • 370
  • 1
  • 14
0

use encodeURIComponent(url) instead of using pure url in window.open

This function encodes special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #

More info here

Ali Sheikhpour
  • 10,475
  • 5
  • 41
  • 82