如何将'window'JSObject从一个浏览器传递到另一个浏览器?

时间:2017-09-20 20:05:29

标签: javafx webview jxbrowser jsobject

使用JavaFx WebView,我可以获得浏览器实例[1]的“窗口”:

// 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实现此目的?

1 个答案:

答案 0 :(得分: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 Bridge API的更多信息