JxBrowser LoadURL / LoadHTML

时间:2018-02-26 18:04:31

标签: javascript java html jxbrowser

从本地目录加载html文件时,我遇到了JxBrowser的问题。我在我的项目中使用了loadHTML和loadURL。在下面的例子中,当我在browserInvokeAndWait方法中使用loadURL时,我发现它需要太长时间,并且无法根据需要引用我的Javascript库。我试图在我加载的页面中启用按钮,但由于页面无法加载自身,因此无法访问任何已加载的元素。代码如下:     package src.java;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.swing.JFrame;

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.Callback;
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;
import com.teamdev.jxbrowser.chromium.dom.events.DOMEvent;
import com.teamdev.jxbrowser.chromium.dom.events.DOMEventListener;
import com.teamdev.jxbrowser.chromium.dom.events.DOMEventType;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.events.ScriptContextAdapter;
import com.teamdev.jxbrowser.chromium.events.ScriptContextEvent;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

public class VisualFrame {

public VisualFrame(final Graph<GNode> dagGraph, final GNode rootGNode, final Browser browser, final BrowserView view, final JFrame frame){
    frame.setTitle("Visualisation");
    frame.setResizable(false);

    browser.addScriptContextListener(new ScriptContextAdapter() {
        @Override
        public void onScriptContextCreated(ScriptContextEvent event) {
            Browser browser = event.getBrowser();
            JSValue window = browser.executeJavaScriptAndReturnValue("window");
            window.asObject().setProperty("java", new CytoData(dagGraph, rootGNode));
            JSValue document = browser.executeJavaScriptAndReturnValue("document");
            document.asObject().setProperty("java", new Graph<GNode>());
        }
    });


    browser.addLoadListener(new LoadAdapter() {
        @Override
        public void onFinishLoadingFrame(FinishLoadingEvent event) {
            if (event.isMainFrame()) {
                System.out.println("Has Reached");
                event.getBrowser().executeJavaScript("var nodes = [];"
                        + "var myArray = new Array();"
                        + "myArray = new Array(window.java.getNodes());"
                        + "var nodes = myArray.toString();"
                        + "nodes = nodes.replace('[','');"
                        + "nodes = nodes.replace(']','');"
                        + "nodes = nodes.split(',');"
                        + "var cy = cytoscape({"
                        + "container: document.getElementById('cy'),"
                        + "boxSelectionEnabled: false,"
                        + "autounselectify: true,"
                        + "style: cytoscape.stylesheet()"
                        + ".selector('node')"
                        + ".css({'content': 'data(id)'})"
                        + ".selector('edge')"
                        + ".css({'curve-style': 'bezier','target-arrow-shape': 'triangle',"
                        + "'width': 4,'line-color': '#ddd','target-arrow-color': '#ddd'})"
                        + ".selector('.highlighted')"
                        + ".css({'background-color': '#61bffc','line-color': '#61bffc',"
                        + "'target-arrow-color': '#61bffc',"
                        + "'transition-property': 'background-color, line-color, target-arrow-color',"
                        + "'transition-duration': '0.5s'}),"
                        + "});"
                        + "var elementCounter = 0;"
                        + "for (i = 0; i < window.java.getSizeOfDAG(); i++) {"
                        + "var currentNode = nodes[i].trim();"
                        + "var eles = cy.add({group: 'nodes', data: { id:currentNode}});"
                        + "elementCounter++}"
                        + "elements: [eles];");
                event.getBrowser().executeJavaScript("for (i = 0; i < window.java.getSizeOfDAG(); i++) {"
                        + "var newCurrentNode = nodes[i].trim();"
                        + "window.alert(newCurrentNode);"
                        + "var holdArray = window.java.getLinkedNodeIDs(newCurrentNode);"
                        + "var targetNodes = holdArray.toString();"
                        + "targetNodes = targetNodes.replace('[','');"
                        + "targetNodes = targetNodes.replace(']','');"
                        + "targetNodes = targetNodes.split(',');"
                        + "for (x = 0; x < targetNodes.length; x++){"
                        + "var targetString = targetNodes[x].trim();"
                        + "eles = cy.add({group: 'edges', data: { id: elementCounter, source:newCurrentNode.trim(), target:targetString.trim()}});"
                        + "elementCounter++;"
                        + "cy.layout({"
                        + "name: 'breadthfirst', "
                        + "fit: true, "
                        + "directed: true,"
                        + "padding: 15,"
                        + "spacingFactor: 1,"
                        + "avoidOverlap: true}).run();"
                        + "}}");
            }
        }
    });

    Browser.invokeAndWaitFinishLoadingMainFrame(browser, new Callback<Browser>(){
        @Override
        public void invoke(Browser arg0) {
            browser.loadURL("file:///home/mbax4jo2/workspace/EditDistanceVisualisation/src/src/web/index.html");
        }
    });




    InputStream urlStream = getClass().getResourceAsStream("../web/UserInputForm.html");

    String html = null;

    try (BufferedReader urlReader = new BufferedReader(new InputStreamReader (urlStream))) {
        StringBuilder builder = new StringBuilder();
        String row;
        while ((row = urlReader.readLine()) != null) {
                builder.append(row);
        }
        html = builder.toString();
    }  catch (IOException e) {
            throw new RuntimeException(e);
    }

    final String loadHTMLPath = html;

    DOMDocument document = browser.getDocument();
    final DOMElement documentElement = document.getDocumentElement();
    System.out.println(browser.getHTML());
    if (documentElement != null) {
        try{
            DOMElement element = documentElement.findElement(By.id("resetBtn"));
            element.addEventListener(DOMEventType.OnClick, new DOMEventListener() {
                public void handleEvent(DOMEvent event) {
                    System.out.println(event);
                    browser.loadURL("file:///home/mbax4jo2/workspace/EditDistanceVisualisation/src/src/web/UserInputForm.html");
                    new UserInput(browser, view, frame);
                }
            }, false);
        }catch(NullPointerException e){
            System.out.println("NULL");
        }

    }

    if (documentElement != null) {
        try{
            DOMElement element = documentElement.findElement(By.id("finishBranchBtn"));
            element.addEventListener(DOMEventType.OnClick, new DOMEventListener() {
                public void handleEvent(DOMEvent event) {
                    browser.loadHTML(loadHTMLPath);
                }
            }, false);
        }catch(NullPointerException e){
            System.out.println("NULL");
        }

    }

    if (documentElement != null) {
        try{
            DOMElement element = documentElement.findElement(By.id("backBtn"));
            element.addEventListener(DOMEventType.OnClick, new DOMEventListener() {
                public void handleEvent(DOMEvent event) {
                    browser.loadHTML(loadHTMLPath);
                }
            }, false);
        }catch(NullPointerException e){
            System.err.println("Caught Exception: " + e.getMessage());
        }

    }

    if (documentElement != null) {
        try{
            DOMElement element = documentElement.findElement(By.id("nextBtn"));
            element.addEventListener(DOMEventType.OnClick, new DOMEventListener() {
                public void handleEvent(DOMEvent event) {
                    browser.loadHTML(loadHTMLPath);
                }
            }, false);
        }catch(NullPointerException e){

            System.err.println("Caught Exception: " + e.getMessage());
        }

    }
}
}

我不太明白为什么loadURL需要这么长时间,当我尝试使用loadHTML技术时,我发现这并不起作用。关于这两种方法之间的区别,我遗漏了一些非常基本的东西。

提前致谢, 千斤顶

EDIT Chromium.log 2018年2月27日下午1:45:42 com.teamdev.jxbrowser.chromium.internal.ipc.a run 严重:[0227 / 134542.952445:错误:browser_process_stub.cpp(61)]未在虚拟ProfileManager中实现* BrowserProcessStub :: profile_manager()

IPC日志 - FINE:WRITE:LoadURLMessage {type = LoadURL,uid = 796,url =&#39; file:///home/mbax4jo2/workspace/EditDistanceVisualisation/src/src/web/index.html' ;, frameId = - 1,extraHeaders =&#39; null&#39;,postData =&#39; null&#39;,SocketInfo {cid = 0,bid = 0,channelType = Browser}

  • FINE:READ:OnHandleLoadMessage {type = OnHandleLoad,uid = 9,url =&#39; file:///home/mbax4jo2/workspace/EditDistanceVisualisation/src/src/web/index.html' ;,loadType = 5,loadPolicy = 2,isRedirect = false,isBackForward = false,cancel = false,SocketInfo {cid = 0,bid = 0,channelType = Render}

  • FINE:WRITE:OnHandleLoadMessage {type = OnHandleLoad,uid = 9,url =&#39; file:///home/mbax4jo2/workspace/EditDistanceVisualisation/src/src/web/index.html' ;,loadType = 5,loadPolicy = 2,isRedirect = false,isBackForward = false,cancel = false,SocketInfo {cid = 0,bid = 0,channelType = Render}

  • FINE:READ:OnShouldBeginRequestMessage {type = OnShouldBeginRequest,uid = 878,browserContextId = -1,url =&#39; file:/// home / mbax4jo2 / workspace / EditDistanceVisualisation / src / src / web / index.html&#39;,method =&#39; GET&#39;,resourceType = 0,cancel = false,SocketInfo {cid = 0,bid = -1,channelType = Main} 2018年2月27日下午1:45:42 com.teamdev.jxbrowser.chromium.internal.ipc.MemoryChannelWriter run

  • FINE:WRITE:OnShouldBeginRequestMessage {type = OnShouldBeginRequest,uid = 878,browserContextId = -1,url =&#39; file:/// home / mbax4jo2 / workspace / EditDistanceVisualisation / src / src / web / index.html&#39;,method =&#39; GET&#39;,resourceType = 0,cancel = false,SocketInfo {cid = 0,bid = -1,channelType = Main}

  • FINE:READ:OnDidCommitProvisionalLoadForFrameMessage {type = OnDidCommitProvisionalLoadForFrame,uid = 879,frameId = 2,url =&#39; file:/// home / mbax4jo2 / workspace / EditDistanceVisualisation / src / src / web / index .html&#39;,isMainFrame = true,transitionType = 1,SocketInfo {cid = 0,bid = 0,channelType = Browser}

  • FINE:READ:OnDidFinishLoadMessage {type = OnDidFinishLoad,uid = 889,frameId = 2,validatedURL =&#39; file:/// home / mbax4jo2 / workspace / EditDistanceVisualisation / src / src / web / index .html&#39;,isMainFrame = true,SocketInfo {cid = 0,bid = 0,channelType = Browser}

  • FINE:READ:OnRunJavaScriptDialogMessage {type = OnRunJavaScriptDialog,uid = 890,dialogId = 1,originURL =&#39; file:/// home / mbax4jo2 / workspace / EditDistanceVisualisation / src / src / web / index .html&#39;,acceptLang =&#39;&#39;,messageType = 0,messageText =&#39; bbc&#39;,defaultPromptText =&#39;&#39;,isReload = false,SocketInfo {cid = 0,bid = 0,channelType = Browser}

0 个答案:

没有答案