2012-12-25 28 views

Trả lời

6

Để chạy javascript trong WebView bạn có thể sử dụng phương pháp WebEngine.executeScript().

Và có rất nhiều cách để đánh dấu văn bản bằng javascript. Ví dụ. Highlight word in HTML text (but not markup)

Tất cả với nhau:

WebView webView = new WebView(); 
    final WebEngine engine = webView.getEngine(); 
    engine.load("https://stackoverflow.com/questions/14029964/execute-a-javascript-function-for-a-webview-from-a-javafx-program"); 

    engine.getLoadWorker().stateProperty().addListener(
      new ChangeListener<State>() { 
       @Override 
       public void changed(ObservableValue ov, State oldState, State newState) { 
        if (newState == State.SUCCEEDED) { 
         engine.executeScript(
           "function highlightWord(root,word){" 
           + " textNodesUnder(root).forEach(highlightWords);" 
           + "" 
           + " function textNodesUnder(root){" 
           + " var n,a=[],w=document.createTreeWalker(root,NodeFilter.SHOW_TEXT,null,false);" 
           + " while(n=w.nextNode()) a.push(n);" 
           + " return a;" 
           + " }" 
           + "" 
           + " function highlightWords(n){" 
           + " for (var i; (i=n.nodeValue.indexOf(word,i)) > -1; n=after){" 
           + "  var after = n.splitText(i+word.length);" 
           + "  var highlighted = n.splitText(i);" 
           + "  var span = document.createElement('span');" 
           + "  span.style.backgroundColor='#f00';" 
           + "  span.appendChild(highlighted);" 
           + "  after.parentNode.insertBefore(span,after);" 
           + " }" 
           + " }" 
           + "}" 
           + "\n" 
           + "highlightWord(document.body,'function');"); 
        } 
       } 
      }); 


    Scene scene = new Scene(webView, 500, 500); 

    primaryStage.setTitle("Hello World!"); 
    primaryStage.setScene(scene); 
    primaryStage.show(); 
-1

Bạn có thể sử dụng để thực hiện một ScriptEngine javascript. khởi ScriptEngine, sau đó tải các tập lệnh vào và đánh giá nó, như thể hiện trong mã dưới đây đề cập

ScriptEngineManager manager = new ScriptEngineManager(); 
ScriptEngine engine = manager.getEngineByName("JavaScript"); 

// JavaScript code in a String 
String script = "function hello(arg) { print(arg); }"; 

// evaluate script 
engine.eval(script); 
+2

'ScriptEngine' cho phép bạn thực hiện một kịch bản nhưng không phải để thực hiện một kịch bản trong bối cảnh của một' mô hình tài liệu WebEngine'. – jewelsea

Các vấn đề liên quan