JxBrowser LoadURL/LoadHTML
У меня возникают проблемы с JxBrowser при загрузке файлов HTML из моего локального каталога. Я использовал loadHTML и loadURL в моем проекте. В приведенном ниже примере, когда я использую loadURL внутри метода browserInvokeAndWait, я нахожу, что это занимает слишком много времени и не может ссылаться на мою библиотеку Javascript по мере необходимости. Я пытаюсь включить кнопки на загруженной странице, но не могу получить доступ ни к одному из загруженных элементов, поскольку страница не может загрузить себя. Код ниже: пакет 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, я обнаруживаю, что это не работает. Я упускаю что-то совершенно фундаментальное в отношении разницы между этими двумя методами.
Заранее спасибо Джек
РЕДАКТИРОВАТЬ Chromium.log 27 февраля 2018 г. 13:45:42 com.teamdev.jxbrowser.chromium.internal.ipc.a выполнить SEVERE: [0227/134542.952445: ОШИБКА:browser_process_stub.cpp(61)] Не реализовано, достигнуто в виртуальном ProfileManager *BrowserProcessStub::profile_manager()
Журнал IPC - FINE: WRITE: LoadURLMessage {type = LoadURL, uid = 796, url = 'file: ///home/mbax4jo2/workspace/EditDistanceVisualisation/src/src/web/index.html', frameId = -1, extraHeaders = 'null', postData = 'null', SocketInfo {cid =0, bid =0, channelType=Browser}
FINE: READ: OnHandleLoadMessage {type = OnHandleLoad, uid = 9, url = 'file: ///home/mbax4jo2/workspace/EditDistanceVisualisation/src/src/web/index.html', loadType = 5, loadPolicy = 2, loadPolicy = 2 = false, isBackForward = false, cancel = false, SocketInfo {cid =0, bid =0, channelType = Render}
FINE: WRITE: OnHandleLoadMessage {type = OnHandleLoad, uid = 9, url = 'file: ///home/mbax4jo2/workspace/EditDistanceVisualisation/src/src/web/index.html', loadType = 2, loadPolicy = = false, isBackForward = false, cancel = false, SocketInfo {cid =0, bid =0, channelType = Render}
FINE: READ: OnShouldBeginRequestMessage {type = OnShouldBeginRequest, uid = 878, browserContextId = -1, url = 'file: ///home/mbax4jo2/workspace/EditDistanceVisualisation/src/src/web/inETx =.html. ', resourceType=0, cancel=false, SocketInfo{cid=0, bid=-1, channelType=Main} 27 февраля 2018 13:45:42 com.teamdev.jxbrowser.chromium.internal.ipc.MemoryChannelWriter run
FINE: WRITE: OnShouldBeginRequestMessage {type = OnShouldBeginRequest, uid = 878, browserContextId = -1, url = 'file: ///home/mbax4jo2/workspace/EditDistanceVisualisation/src/src/web/index.h = ', resourceType=0, cancel=false, SocketInfo{cid=0, bid=-1, channelType=Main}
FINE: READ: OnDidCommitProvisionalLoadForFrameMessage {type = OnDidCommitProvisionalLoadForFrame, uid = 879, frameId = 2, url = 'file: ///home/mbax4jo2/workspace/EditDistanceVisualisation/srhme/ra_mex_m_fl_RuR_FR_WR_FR = 1, SocketInfo {cid =0, bid =0, channelType=Browser}
FINE: READ: OnDidFinishLoadMessage {type = OnDidFinishLoad, uid = 889, frameId = 2, validatedURL = 'file: ///home/mbax4jo2/workspace/EditDistanceVisualisation/src/src/web/index.MainFrameSoft_MefoMisfo_Mentme is, IsFrame {cid =0, bid =0, channelType=Browser}
FINE: READ: OnRunJavaScriptDialogMessage {type = OnRunJavaScriptDialog, uid = 890, dialogId = 1, originURL = 'file: ///home/mbax4jo2/workspace/EditDistanceVisualisation/src/src/web/index.html', acceptdex.html ', accept messageType =0, messageText = 'bbc', defaultPromptText = '', isReload = false, SocketInfo {cid =0, bid =0, channelType=Browser}