简体   繁体   中英

Can't load CSS/JS on javafx Webview

I am having trouble getting css/js to show up on a Webview.

Here is what I am doing:

initializing the webview and engine

WebView browser = new WebView();
WebEngine webEngine = browser.getEngine();
webEngine.setJavaScriptEnabled(true);

This is where I load html content:

htmlViewImgBtn.addEventHandler(MouseEvent.MOUSE_CLICKED,
    new EventHandler<MouseEven
        @Override
        public void handle(MouseEvent event){

            if (counter == 0){
            contentContainer.getChildren().addAll(browser);
            webEngine.loadContent(export.getHTML(note));
            //browser.getEngine().load("http://stackoverflow.com/questions/34554583/cant-load-css-js-on-javafx-webview");
            contentContainer.getChildren().remove(noteContent);
            counter = 1;
           }

           else {
           contentContainer.getChildren().remove(browser);
           contentContainer.getChildren().addAll(noteContent);
           counter = 0;
           }
       }
});

Note: The commented code works when loading a website onto the webview, no issues. But Still does not work for the content I am loading.

The content (HTML) that is loaded looks looks like this:

<link href="prism.css" rel="stylesheet" type="text/css" />
<script src="prism.js" type="text/javascript"></script>
<pre><code class="language-java">System.out.println("Hello");
</code></pre>

Also, the css and js files are in the same directory as the java file

I can confirm that the html works by loading it on a web browser, What am I missing?

Blockquote

I was able to get it working by modifying the html as such:

"<link href=\"" + getClass().getResource("./prism.css") + "\"" + " rel=\"stylesheet\"" + " type=\"text/css\"" +  " />\n" + 
"<script src=\"" + getClass().getResource("./prism.js") + "\"" + " type=\"text/javascript\"" + "></script>\n" +
(rest of html);

You can use ResourceLoader to load HTML, js and css which are located in the same directory as the Java class.

    URL url = getClass().getResource("index.html");
    webEngine.load(url.toExternalForm());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM