AFAIKS, that's exactly what your javascript snippet also does, isn't it?
I run a very recent bzr emacs, so maybe the problem is already solved in between 24.1 and now...