jquery - 如何在 javafx webview 中包含 jquery?

标签 jquery webview javafx

如标题所示,我需要在 jfx webview 中包含 jquery。到目前为止,我可以包含来自资源文件夹的 css 样式表,顺便说一句,我的应用程序是 swing,但使用 javafx 中的 webview 可以获得更好的 css 支持,因为 swing 中的 jtextpane 不支持太多 css。

最佳答案

我确实喜欢这个主意Stephen Katulka's答案,如果斯蒂芬的方法适合你,这可能是一个更好的答案。

<小时/>

更新:我刚刚查看了 shankar's answer 中的链接并且那里的代码与此答案中包含的示例代码相同。

<小时/>

我使用下面的函数在 WebView 中使用 jQuery:

/**
 * Executes a script which may reference jQuery function on a document.
 * Checks if the document loaded in a webEngine has a version of jQuery corresponding to 
 * the minimum required version loaded, and, if not, then loads jQuery into the document 
 * from the default JQUERY_LOCATION.
 * @param engine the webView engine to be used.
 * @Param jQueryLocation the location of the jQuery script to be executed.
 * @param minVersion the minimum version of jQuery which needs to be included in the document.
 * @param script provided javascript script string (which may include use of jQuery functions on the document).
 * @return the result of the script execution.
 */ 
private static Object executejQuery(final WebEngine engine, String minVersion, String jQueryLocation, String script) {
  return engine.executeScript(
    "(function(window, document, version, callback) { "
      + "var j, d;"
      + "var loaded = false;"
      + "if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {"
      + "  var script = document.createElement(\"script\");"
      + "  script.type = \"text/javascript\";"
      + "  script.src = \"" + jQueryLocation + "\";"
      + "  script.onload = script.onreadystatechange = function() {"
      + "    if (!loaded && (!(d = this.readyState) || d == \"loaded\" || d == \"complete\")) {"
      + "      callback((j = window.jQuery).noConflict(1), loaded = true);"
      + "      j(script).remove();"
      + "    }"
      + "  };"
      + "  document.documentElement.childNodes[0].appendChild(script) "
      + "} "
      + "})(window, document, \"" + minVersion + "\", function($, jquery_loaded) {" + script + "});"
  );
}

该函数源自此sample gist将 jQuery 注入(inject)到加载到 WebView 中的文档中。

请注意,该函数要求在执行注入(inject) jQuery 的脚本之前将文档加载到 WebView 中。您可以通过向 WebEngine 的 document 属性添加监听器并仅在设置文档后触发注入(inject) jQuery 的函数来确保文档已加载。

<小时/>

您还可以将 jQuery 引用直接包含在加载的 html 中,而不是注入(inject)它们。直接包含技术的一个示例是此示例,它显示 jQuery DatePicker在 JavaFX WebView 屏幕中。

关于jquery - 如何在 javafx webview 中包含 jquery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19446510/

相关文章:

javascript - 将 Id 名称的一部分放入变量中

javascript - 在 Backbone 中的 AJAX 请求中模型更改后重新呈现

javascript - 即使在 jQuery 脚本中执行 element.preventDefault() 后, anchor 标记也会跟随 url

swift - 在命令行中使用 WebView : found nil error while unwrapping

webview - 带有 WKWebView 查看器的简单 OS X 应用程序

java - 如何在javaFX中显示所有控制台消息?

java - 向我的游戏添加第二个关卡

javascript - 为什么它在我的 if/else 语句中循环遍历 'else'?

javascript - WebView 代码在 Android 4.4.2 (API 19) 模拟器上生成 Uncaught TypeError 和 Uncaught ReferenceError 错误

scala - 为什么 sbt 第二次运行 gui 应用程序失败?