2017-09-20 106 views
0

使用JavaFX的WebView,我可以得到一個瀏覽器實例的「窗口」 [1]:如何將'window'JSObject從一個瀏覽器傳遞給另一個瀏覽器?

// Java code 
netscape.javascript.JSObject win = (JSObject) webengine.executeScript("window"); 

然後我就可以通過這個JSObject另一個瀏覽器實例[2],並在此瀏覽器的JavaScript,我可以操作和訪問的第一個瀏覽器實例[1]這樣的DOM,變量和函數:

// Javascript code 
// get 'window' netscape.javascript.JSObject of 'browser1' webview 
// control from the getWindow() method in my linked Java class 
var window1 = javaObj.getWindow("browser1"); 

// get variables defined in 'browser1' javascript 
var rString = window1.myString; 
var rNum = window1.myNumber; 

// execute the 'myAlert' function on 'browser1' and pass variables in 
window1.myAlert(rString + " - " + rNum + "<br><br>" + Date()); 

// manipulate the DOM on 'browser1' 
window1.document.getElementById("myLabel").style.backgroundColor = "red"; 

如何我jxBrowser實現這一目標?

回答

0

JxBrowser提供了類似的功能,允許將Java對象注入JavaScript並從JavaScript代碼調用其方法,但JxBrowser不使用netscape.javascript.JSObject類。下面的例子演示了這個想法如何使用Java對象注入到從JavaScript訪問Java對象的方法:

import com.teamdev.jxbrowser.chromium.Browser; 
import com.teamdev.jxbrowser.chromium.JSValue; 
import com.teamdev.jxbrowser.chromium.dom.By; 
import com.teamdev.jxbrowser.chromium.dom.DOMDocument; 
import com.teamdev.jxbrowser.chromium.dom.DOMElement; 

public class JavaScriptJavaSample { 
    public static void main(String[] args) { 
     Browser browser = new Browser(); 

     JSValue window = browser.executeJavaScriptAndReturnValue("window"); 

     // Inject Java object into JavaScript and associate it with 
     // the window.javaWindow property. 
     JavaWindow javaWindow = new JavaWindow(browser); 
     window.asObject().setProperty("javaWindow", javaWindow); 

     // You can access public fields of the injected Java object 
     // and modify their values from JavaScript. For example: 
     // 
     // window.javaWindow.myString = 'Hello, Java'; 
     // window.javaWindow.myNumber = 123; 
     // window.document().getElementById('myLabel').setAttribute('name', 'myName'); 
    } 

    public static class JavaDocument { 

     private DOMDocument document; 

     public JavaDocument(DOMDocument document) { 
      this.document = document; 
     } 

     public DOMElement getElementById(String id) { 
      return document.findElement(By.id(id)); 
     } 
    } 

    public static class JavaWindow { 
     public String myString; 
     public int myNumber; 

     private Browser browser; 

     public JavaWindow(Browser browser) { 
      this.browser = browser; 
     } 

     public JavaDocument document() { 
      return new JavaDocument(browser.getDocument()); 
     } 
    } 
} 

您可以在https://jxbrowser.support.teamdev.com/support/solutions/folders/9000074803

在文章閱讀更多關於JavaScript的Java API橋
相關問題