Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the DOM from webview in atom Electron

Is it possible to scrape html from the webview element in the atom electron desktop development toolkit, I am trying to access the DOM but i get nothing back, i have tried a document.links in the console at runtime but i get empty properties and objects in return?

 window.onresize = doLayout;
 var isLoading = false;

onload = function() {
var webview = document.querySelector('webview');
doLayout();

var t = webview.executeJavaScript("console.log(document.links);");

document.querySelector('#back').onclick = function() {
webview.goBack();
};

<object is="browserplugin" type="application/browser-plugin" id="browser-plugin-1" style="flex: 1 1 auto;"></object>
like image 812
apaul Avatar asked Sep 14 '16 17:09

apaul


1 Answers

Your console.log is logging to the webview's console, not your parent renderer process' console. Run document.querySelector('webview').openDevTools() from your parent renderer (after you have a src on the webview, it's additional methods aren't available until then). This will open another dev tools window. From that console, you should see your log. Note that webviews and the renderer hosting the webview are two separate webContents instances and two separate renderer processes. You can communicate between them or the main process via IPC.

Not sure what your goals are, but if you want to do DOM manipulation in a webview, I'd recommend using a preload script. This script gets run before the webview's JS and gives you access to all node.js and renderer electron APIs as well as the DOM. executeJavaScript is going to be a long difficult road, whereas preload scripts were built for this kind of use case.

Here's an example demonstrating 1) opening the devtools of a webview, 2) running a preload script in the webview's context that access the DOM, 3) communicating between the parent renderer process and it's child webview process via IPC: https://github.com/ccnokes/electron-tutorials/tree/master/preload-scripts

like image 100
ccnokes Avatar answered Sep 23 '22 13:09

ccnokes