如何在服务器端渲染 javascript
我使用 java.net.URL 和输入流获取字符串中的网页内容。
我遇到的问题是我的 javascript 没有呈现,并且我得到的是响应。
<html>
<head></head>
<body>
<script>
document.write("<h1>hello world!</h1>");
</script>
</body>
</html>
假设这是用 HTML 文件编写的代码.. 现在我想要当我获取字符串中的网页内容时.. javascript 应该呈现..
<html>
<head></head>
<body>
<h1>Hello World!</h1>
</body>
</html>
像这样.. 我该怎么做???
i m getting a web page content in a string by using java.net.URL and Input Streams.
the problem i m having that my javascript is not rendering and i m getting the as it is response.
<html>
<head></head>
<body>
<script>
document.write("<h1>hello world!</h1>");
</script>
</body>
</html>
suppose this is the code written in HTML file .. now i want when i get the webpage content in string .. the javascript should b rendered..
<html>
<head></head>
<body>
<h1>Hello World!</h1>
</body>
</html>
like this .. how i can do that ????
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JavaScript 不会由 java.net.URL 自动执行。带有内联 JavaScript 的 HTML 文件仅被视为任何其他纯文本文件,并且不会以任何方式进行解析。不构建 DOM,不执行 JavaScript,不应用 CSS。要执行 JavaScript,您需要做的是使用 HtmlUnit 之类的内容来解析它。
不过,如果您可以控制 HTML,我建议您将
document.write()
语句替换为静态 HTML。当然,一个非常基本的替代方案是仅对正则表达式document\.write\(([^\)]+)\);? 进行搜索,并将其替换为第一个捕获的匹配项。
The JavaScript won't be executed automagically by java.net.URL. The HTML file with the inline JavaScript is just seen as any other plain text file and isn't parsed in any way. No DOM is built, no JavaScript is executed, no CSS applied. What you need to do to get the JavaScript executed is to parse it with something like HtmlUnit.
If you have control of the HTML, though, I'd recommend you to just replace the
document.write()
statements with static HTML. A very rudimentary alternative is of course to just do a search on the regular expressiondocument\.write\(([^\)]+)\);?
and replace it with the first captured match.https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/LiveConnect/ JSObject
提到的 netscape.javascript.JSObject 类中的 eval 方法可能就是您正在寻找的(尽管我不确定它是否负责 DOM 操作以及是否可以跨浏览器工作)。
祝你好运!
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/LiveConnect/JSObject
The eval method in the mentioned netscape.javascript.JSObject class might be what you're looking for (though I'm not sure if it takes care of DOM manipulation and if it works across browsers).
Good luck!