Accessing the DOM


#1

HI. I’ve started playing around with Electron and i’m not sure how to access the DOM. I have a script which uses a:contains(“something here”) to find something on the page. It works fine as a chrome content script but it’s not working with the webview. i read through the docs and looked at the renderer processes API but i couldn’t find what i was looking for. Any ideas? Cheers!


#2

On the Renderer side, you should always at least be able to use document.querySelector to find elements on the page.


#3

My problem is I can’t figure out how to get any information back from webview. I’m reading a json from remote page and want to have the result available in my main program.

Here’s my code.

<!DOCTYPE html>
<html>
<body>
    <webview
        id="myWebView"
        src="https://myjsonservice.ee/api/user.json"
    </webview>

    <script>
        onload = function() {
            var domReady = function domReady() {
                webview.openDevTools()
                var code = 'console.log(JSON.parse(document.body.lastChild.innerHTML).result.user_id)'
                webview.executeJavaScript(code)
                // everything works so far
                // =>> (program):1 562fae8e11c0da1600b1a0a2
                
                code = "require('ipc').send('user', JSON.parse(document.body.lastChild.innerHTML).result.user_id)"
                webview.executeJavaScript(code)
                // =>> Uncaught ReferenceError: require is not defined
            }
            var webview = document.getElementById("myWebView")
            webview.addEventListener("dom-ready", domReady)
        }
    </script>
</body>
</html>

#4

Web views aren’t really designed for that kind of thing. You probably want an AJAX library. There are some topics here that should be able to help you with that if you search for them.


#5

Thank You,
But how about geting content from BrowserWindow?

app.on('ready', function() {
    authWindow = new BrowserWindow({ width: 900, height: 600, show: true })
    authWindow.loadUrl('https://myjsonservice.ee/api/user.json')
...

#6

If you use an AJAX library, you won’t need to access the DOM … you’ll just get the JSON in a string. I don’t think you can access a DOM for JSON anyway … since there’s no HTML document. (It is a Document Object Model, after all.)


#7

Unfortunately getting stright to json is out of question in this case.
Teh API requiring authentication with some bigger providers (G, FB, MS, …) so it doesnot give JSON back right away but only after user interaction (ie. logging in with G). Only after that I will get the JSON which in turn contains authentication tokens for my further requests to this API (which I can do without webview then).

I found an awkward solution saving JSON to file and reading from there:

authWindow.webContents.savePage('user.json', 'HTMLComplete', function(error))