开发者

How do you programmatically execute javascript as if from the browser bar?

For example if you type in the browser bar javascript:alert('hai'); it shows a pop up. Is that possible to do in a p开发者_如何学编程rogramming language?

For example in java would I be able to connect to a website, and execute it's javascript somehow in my program?

Example:

Javascript in website:

function setStatus(a) {
    if (a == 1) status1 = true;
    else if (a == 2) status2 = true;
    else if (a == 3) status3 = true
}

Java program:

URL site = new URL("http://somesite.com/page.html");
URLConnection siteConnect = site.openConnection();
siteConnect.connect();

Would I be able to execute setStatus(1) setStatus(2) setStatus(3) inside the java program? How could it be done?


You're looking for an environment that includes both a Javascript engine and the browser DOM and JS builtins; therefore your easiest bet is going to be something like a browser.

First stop for you should probably be HTMLUnit , which has Javascript support via Rhino and provides all the browser-specific JS objects. That may be everything you need.

If you want to go deeper, you could hook into a full browser engine by developing against Webkit. Two ports to look at are QtWebkit (if speed is not a criteria for you) or Google's Chromium. Beware that setting either of those up will be a time investment.


Not with just plain Java. Your browser can do that because it has a Javascript runtime installed, Java doesn't have that by default.

One option you may want to consider is Rhino, a Javascript implementation in Java. You'd be able to run most standard Javascript this way, however anything that interacts with the browser's DOM (like the window object) may not work correctly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜