TruckMovers / cordova-plugin-remote-injection

DEPRECATED: Cordova plugin to allow a remote site to interact with cordova's javascript APIs when loaded within a cordova app.
Apache License 2.0
91 stars 95 forks source link

Inject cordova before page load #28

Closed ccorcos closed 7 years ago

ccorcos commented 7 years ago

Is there any way to inject window.cordova before the page runs its JavaScript?

I see we're using onWebViewDidFinishLoad here: https://github.com/TruckMovers/cordova-plugin-remote-injection/blob/master/src/ios/CDVRemoteInjectionUIWebViewDelegate.m#L67

bradleyjames commented 7 years ago

It's not possible to configure when cordova is injected by the plugin. It is possible to inject your javascript after cordova is injected in the deviceready event. But if your site is meant to work in a non cordova mode you'd need some way to inject your javascript that's not reliant on cordova. You'd have to do some testing to determine if this possible with exposed HTML DOM events like page load or dom ready.

ccorcos commented 7 years ago

Well maybe you could make the HTTP request outside of the WebView and inject the script directly into the HTML file.

It looks like all scripts are always executed in order:

<script type="text/javascript">
    console.log("before anything")
</script>

<html>

<head>
    <script type="text/javascript">
        console.log("head")
    </script>
</head>

<body>
    <script type="text/javascript">
        console.log("before")
    </script>
    <script type="text/javascript" src="a.js"></script>
    <script type="text/javascript" src="b.js"></script>
    <script type="text/javascript">
        console.log("after")
    </script>
</body>

</html>

a.js

window.a = true
console.log('b', window.b)

b.js

window.b = true
console.log('a', window.a)

console output

[Log] before anything (index.html, line 2)
[Log] head (index.html, line 10)
[Log] before (index.html, line 16)
[Log] b – undefined (a.js, line 2)
[Log] a – true (b.js, line 2)
[Log] after (index.html, line 21)

we still have to wait for deviceready to do anything with cordova, but at least this way we could set something like window.__isCordova = true in our injected script so the page knows its inside a cordova application when the JS is executed.