Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript window.open url with spaces and %

I'm trying window.open with a url with spaces:

var msg = 'Hello, world!';  
var url = 'http://yoursite.com';  
var link = 'http://www.twitter.com/share?text=' + msg + '&url=' + url; 
window.open(link);

Running this code will open a new window with http://twitter.com/share?text=Hello,%2520world!&url=http://yoursite.com.

What happens is that the space in msg is converted to %20, then the '%' is converted to %25. As a workaround, i added:

msg = msg.replace(/\s/g, '+');

But are there other chars i need to watch out for or is there a better workaround?

like image 973
nymo Avatar asked Mar 15 '11 22:03

nymo


People also ask

What is window open() in JavaScript?

open() The open() method of the Window interface loads a specified resource into a new or existing browsing context (that is, a tab, a window, or an iframe) under a specified name.

How to open the page in new window by JavaScript?

open() method is used to open a new browser window or a new tab depending on the browser setting and the parameter values. Syntax: window. open(URL, name, specs, replace);

Can window open return a value?

the pop up window must be able to return a value to the "parent". Typically this value is a Boolean but it could be any simple type (e.g.: string, int, etc.) solution must work even if the URL of the content is from different domain.

Why is space %20 in URL?

A space is assigned number 32, which is 20 in hexadecimal. When you see “%20,” it represents a space in an encoded URL, for example, http://www.example.com/products%20and%20services.html.


1 Answers

Try this instead:

var msg = encodeURIComponent('Hello, world!');  
var url = encodeURIComponent('http://www.google.com');  
var link = 'http://twitter.com/intent/tweet?text=' + msg + '&url=' + url; 
window.open(link); 

Note the different Twitter url and the encoding of the query string params.

like image 128
DTRx Avatar answered Oct 04 '22 22:10

DTRx