Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error evaluating injectedJavaScript: This is possibly due to an unsupported return type. Try adding true to the end of your injectedJavaScript string. #341

Closed
EgidioCaprino opened this issue Feb 13, 2019 · 32 comments

Comments

@EgidioCaprino
Copy link

Hello,

We're trying to migrate from react-native WebView. Replacing import { WebView } from 'react-native' with import { WebView } from 'react-native-webview' gives us this error when the component is mounted:

Error evaluating injectedJavaScript: This is possibly due to an unsupported return type. Try adding true to the end of your injectedJavaScript string.

I've tried to add ; true or ; return true at the end of the injected script but we still get the same error.

Do you know how we can fix it or identify the underlying problem?

@RobinUS2
Copy link

What worked for us was this:

injectJavaScript(
                "window.callSomeFunction(); void(0);",
              )

@EgidioCaprino
Copy link
Author

EgidioCaprino commented Feb 13, 2019

That didn't work 😢

@EgidioCaprino
Copy link
Author

EgidioCaprino commented Feb 13, 2019

I've noticed that if I pause between one call to webView.injectJavaScript and the next one with the debugger it does not throw an error

@EgidioCaprino
Copy link
Author

Throttling the calls to injectJavaScript seems to have fixed the problem.

this.injectJavaScript = throttle(this.injectJavaScript.bind(this), 500);

@matthewfbenjamin
Copy link

@EgidioCaprino's solution worked for me. I had to stop using the injectedJavaScript prop and used the method instead to inject the same string.

@EgidioCaprino
Copy link
Author

This problem still occurs for us 😢

@legion-zver
Copy link

See your JS code carefully, this error is due to the fact that WebView can not execute JS code!

@EgidioCaprino
Copy link
Author

The same code was working with WebView imported from react-native 😕

@Titozzz
Copy link
Collaborator

Titozzz commented Feb 19, 2019

Android or iOS ?

@meshaabi
Copy link

meshaabi commented Feb 20, 2019

just upgraded from 2.10 to the current latest and started running into this. The injection seems a wee bit more unreliable in general after the upgrade. (iOS)

@Titozzz
Copy link
Collaborator

Titozzz commented Feb 20, 2019

This seems to happen when you inject code too early before webview is loaded, but I'm not sure

@sillysachin
Copy link

Facing it with some form submission .
Working -
const jsCodeHello = 'alert("hello")';
Not Working -

const jsCode = `
     document.getElementById("name").value = "${name}"; 
     document.f1.submit(); 
`; 

@sillysachin
Copy link

sillysachin commented Feb 23, 2019

Fixed using a timer.

const jsCode = `
    setTimeout(() => {
        document.getElementById("name").value = "${name}"; 
        document.f1.submit(); 
    }, 100);
`;

@Titozzz
Copy link
Collaborator

Titozzz commented Mar 28, 2019

When I inject stuff inside the webview i'll always wrap it inside a function and instantly execute it. It allows me to avoid wrong return types:

(function(lol){
	//do stuff
})()

@Titozzz Titozzz closed this as completed Mar 28, 2019
@AndrewHenderson
Copy link

@legion-zver is right. Try running that same code in a Web browser console and verify that it can execute. There is likely a minor syntax error.

@fangasvsass
Copy link

i have the same issue , The same code was working with WebView imported from react-native,Who has a good solution?

@andrevvalle
Copy link

andrevvalle commented Apr 12, 2019

This works for me!

this.webviewRef.injectJavaScript(this.onLoadGetStore);

Screen Shot 2019-04-12 at 14 37 09

@brandonmoon
Copy link

This is really late, but for anyone else stuck on this issue and having problems finding a solution, for me the issue was that in the original react-native WebView I could just call postMessage(), but this library changed it to window.ReactNativeWebView.postMessage(). Since postMessage is now undefined, your existing code will throw an error, and the new library responds with the generic (and very unhelpful) error message:

Error evaluating injectedJavaScript: This is possibly due to an unsupported return type. Try adding true to the end of your injectedJavaScript string.

You will see this message for any JS error thrown by the webview. By updating your postMessage() calls you should be able to get things working again. Good luck!

TL;DR => Replace postMessage() calls with window.ReactNativeWebView.postMessage() to fix this error.

@Iamhere
Copy link

Iamhere commented Jun 14, 2019

In my case I replaced injectedJavaScript prop with injectJavaScript() method and it fixed the error.

@Nantris
Copy link

Nantris commented Jul 23, 2019

@sillysachin's solution worked for me, and even with a large injection on a very slow simulator, using 0 for the amount of time works just as well as 100.

@davidcort
Copy link

This bug is present in iOS <= 9.2. For recent releases this bug is not present.

@KangYoosam
Copy link

using setTimeout solved my problem as described here.
#341 (comment)

@Juanjo4U
Copy link

Juanjo4U commented Jan 23, 2020

try and catch works fine, if you are adding an event to an element that does not exist you are gonna get (Error evaluating injectedJavaScript: This is possibly due to an unsupported return type. Try adding true to the end of your injectedJavaScript string.
#)
so if u use try and catch if the element does not exist u are gonna get whatever you put in catch, but if element exist you are gonna get what u put on try, don't forget to add a true at the end of the injection.

for example I used this:

const INJECTED_JS = `
      try{
            document.querySelector('form[data-refresh-athlete=true]').addEventListener('submit', _ => {
                window.ReactNativeWebView.postMessage(
                    JSON.stringify({
                        requireUserFecth: true,
                    }),
                )
            })
        } catch(e) {
            window.ReactNativeWebView.postMessage(
                JSON.stringify({
                    injected: false,
                }),
            )
        }
        true;
`

@lotusshinoaki
Copy link

lotusshinoaki commented Feb 7, 2020

react-native-webview outputs the message "Please add true to the end of the inserted JavaScript string" regardless of the error that occurred in injectedJavaScript.
The latest version of react-native-webview adds a dump of the actual error that occurred at the end of the message.
This will help identify the actual cause.
https://github.com/react-native-community/react-native-webview/blob/5e8b4d5c2b08b982b1f80ecd34160597ec482a4f/ios/RNCWebView.m#L999

In most cases, you will see the error "WKWebView was invalidated."

@GreatAuk
Copy link

This seems to happen when you inject code too early before webview is loaded, but I'm not sure

It is not because inject code too early before webview is loaded, the reason is inject code too early before window is loaded
this solution is worked。

@harking
Copy link
Contributor

harking commented Jul 15, 2020

In our error, we were trying to inject during componentWillUnmount to try and clean up some resources the webview was using. Removing this fixed it.

@GreatAuk
Copy link

This seems to happen when you inject code too early before webview is loaded, but I'm not sure

issue still (some time)
this works for me

    `
      try {
        window.onload = function() {
          callFunc()
        }
        if(document.readyState === 'complete') {
         callFunc()
        }
      } catch (err) {
        console.error(err)
      }
      true;
      `
      // it's may be call function for twice

@svpease
Copy link

svpease commented Apr 8, 2021

Had this problem, realized it was a function in my code that was looping indefinitely within the webview. So don't forget to check if that's happening.

@fondue-tech
Copy link

Amazing still issue after 3 years. Crazy.

@ElectricCoffee
Copy link

Yeah I'm having this issue as well.

I've noticed it only happens when I try to call window.ReactNativeWebView.postMessage

@emrahyurttutan
Copy link

emrahyurttutan commented Jul 11, 2023

Fixed using a timer.

const jsCode = `
    setTimeout(() => {
        document.getElementById("name").value = "${name}"; 
        document.f1.submit(); 
    }, 100);
`;

this could be an alternative

<WebView 
javaScriptEnabledAndroid
javaScriptEnabled
injectedJavaScriptBeforeContentLoaded={'document.getElementById("name").value = "${name}";document.f1.submit();'}
/>

@ElectricCoffee
Copy link

Fixed using a timer.

const jsCode = `
    setTimeout(() => {
        document.getElementById("name").value = "${name}"; 
        document.f1.submit(); 
    }, 100);
`;

this could be an alternative

<WebView 
javaScriptEnabledAndroid
javaScriptEnabled
injectedJavaScriptBeforeContentLoaded={'document.getElementById("name").value = "${name}";document.f1.submit();'}
/>

Except it doesn't because you didn't interpolate the string in the injected JS. Replace ' with ` and you're golden.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests