Loading javascript functions to webview in Android Kitkat - javascript

I am having problems with loading javascript functions, which are in external file, into webview in Android Kitkat. My approach for earlier versions was that i implemented my own webview client and in method onPageFinisned i called
mWebView.loadUrl("javascript:" + functions);
later, when i wanted to call some js method, i call same code, like
mWebView.loadUrl("javascript:" + someFunction);
In android kitkat there is new method evaluateJavascript, which replaces my code with calling that javascript functions. My problem is that now this and old approach throw this error:
Uncaught ReferenceError: function is not defined
It seems that problem is in loading that javascript functions to webview but i dont know how to load it other way. Thanks

What works for me is to have the JavaScript functions inside a Web page, in <script> tags:
<html>
<head>
<title>Android GeoWebTwo Demo</title>
<script language="javascript">
function whereami(lat, lon) {
document.getElementById("lat").innerHTML=lat;
document.getElementById("lon").innerHTML=lon;
}
function pull() {
var location=JSON.parse(locater.getLocation());
whereami(location.lat, location.lon);
}
</script>
</head>
<body>
<p>
You are at: <br/> <span id="lat">(unknown)</span> latitude and <br/>
<span id="lon">(unknown)</span> longitude.
</p>
<p><a onClick="pull()">Update Location</a></p>
</body>
</html>
Then, I can successfully use evaluateJavascript():
public void onLocationChanged(Location location) {
StringBuilder buf=new StringBuilder("whereami(");
buf.append(String.valueOf(location.getLatitude()));
buf.append(",");
buf.append(String.valueOf(location.getLongitude()));
buf.append(")");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
browser.evaluateJavascript(buf.toString(), null);
}
else {
browser.loadUrl("javascript:" + buf.toString());
}
}
(both code snippets are from this sample app)
This works on old and new versions of Android. Now, in my case, my JavaScript happens to be messing with the DOM, so I needed a Web page anyway. Yours might have an empty <body>, with the Web page just there to supply the JavaScript functions.

Related

UWP Webview ScriptNotify is not getting trigerred

Need to get callback from webpage to my "WebView" in C# using scriptnotify. But it's not working.
I hosted a webpage locally using node js. Webpage is as below.
<!DOCTYPE html>
<html>
<body>
<h1>The onclick Event</h1>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "latest";
window.external.notify('The script says the doubled value is ' );
}
</script>
</body>
</html>
After that created a UWP app to open the webpage using webview. Added window.external.notify in the JS to get the call back. But not getting the same.
//C# code to get the callback
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
//Added the notification handler here
webView.ScriptNotify += webView_ScriptNotify;
//Navigating to the local page
webView.Navigate(new Uri("http://localhost:8080/"));
}
async void webView_ScriptNotify(object sender, NotifyEventArgs e)
{
//Kept break point here , but it's not getting hit any time.
var jsScriptValue = e.Value;
Debug.WriteLine("Send to debug output.");
}
}
//Added a web view control in xaml file
<Grid>
<WebView x:Name="webView" Height="500"> </WebView>
</Grid>
UWP Webview ScriptNotify is not getting trigerred
Please check WebView document.
To enable an external web page to fire the ScriptNotify event when calling window.external.notify, you must include the page's URI in the ApplicationContentUriRules section of the app manifest. (You can do this in Microsoft Visual Studio on the Content URIs tab of the Package.appxmanifest designer.) The URIs in this list must use HTTPS, and may contain subdomain wildcards (for example, https://.microsoft.com) but they cannot contain domain wildcards (for example, https://.com and https://.). The manifest requirement does not apply to content that originates from the app package, uses an ms-local-stream:// URI, or is loaded using NavigateToString.
So, you need add your uri to the content uri option.

Execute js script into Windows 10 webView

I'd like to run a js function that is not written into loaded html page, for example we have a simple html page with button, and I'd like to disable the button using an external js script:
<!DOCTYPE html>
<html>
<body>
<button id="my_button" type="button" onclick="">Click Me!</button>
</body>
</html>
and I have my script form a file:
function disableFun() {
document.getElementById("my_button").disabled = true;
}
as is mentioned in official doc there is a API method InvokeScriptAsync(string scriptName, string[] arguments) but is mentioned that we must already have the script into html loaded page.
Any advices are apreciated!
P.S. in android we do it very simple webView.loadUrl('my script code')
You can use InvokeScriptAsync with the JavaScript eval function to inject content into the web page.
see Interacting with WebView content section of this document.
So to disable the button, you can use the following codes in your cs file:
String scriptStr = #"document.getElementById('your_buttonId').disabled=true";
await myWebView.InvokeScriptAsync("eval", new String[] {scriptStr});

Delphi TWebBrowser Wont Run Javascript from LocalHost

I have a really simple Delphi XE7 program. It is basically just a TWebBrowser component embedded in a form with no extra code attached, other than a button that fires off the Browser.Navigate method. My understanding is that TWebBrowser is just an ActiveX wrapper for IE.
I am trying to use this to display a very simple page that references the D3 Javascript library (but so far doesn't do anything with it), and the web pages are served from a localhost webserver that is running on my PC using WAMPSERVER.
The web pages run just fine in Chrome or IE 11 (I have Windows 7, 64 bit). But when I try to view them within the Delphi/TWebBrowser program I get the IE error message "An error has occurred on the script on this page" (see image attached). The error seems to occur when trying to access the d3.js javascript library in the d3test/d3 folder on the local host. I have verified that the d3.js file does exist in this folder and this seems to be borne out by the fact that the page runs and displays just fine in both Chrome and IE.
Perhaps there is an issue with having an embedded web browser access locally hosted pages? Additional background -I have also cleared the IE cache, reset the Internet options on the Windows Control Panel, set IE security settings to the minimum level and temporarily disable my Norton Firewall/Virus scanner.
Does anyone have any thoughts on this? I'm really hoping to be able to get some D3 charts embedded in my Windows-based program.
Here also is the html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3 Test</title>
<script type="text/javascript" src="d3\d3.js"></script>
</head>
<body>
Hello World
</body>
</html>
I added answer from your comments below the question so its may
helpful to others
add this meta tag into your web page
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
In this case you should add this class to your code:
type TBrowserEmulationAdjuster = class
private
class function GetExeName(): String; inline;
public const
// Quelle: https://msdn.microsoft.com/library/ee330730.aspx, Stand: 2017-04-26
IE11_default = 11000;
IE11_Quirks = 11001;
IE10_force = 10001;
IE10_default = 10000;
IE9_Quirks = 9999;
IE9_default = 9000;
/// <summary>
/// Webpages containing standards-based !DOCTYPE directives are displayed in IE7
/// Standards mode. Default value for applications hosting the WebBrowser Control.
/// </summary>
IE7_embedded = 7000;
public
class procedure SetBrowserEmulationDWORD(const value: DWORD);
end platform;
class function TBrowserEmulationAdjuster.GetExeName(): String;
begin
Result := TPath.GetFileName( ParamStr(0) );
end;
class procedure TBrowserEmulationAdjuster.SetBrowserEmulationDWORD(const value: DWORD);
const registryPath = 'Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION';
var
registry: TRegistry;
exeName: String;
begin
exeName := GetExeName();
registry := TRegistry.Create(KEY_SET_VALUE);
try
registry.RootKey := HKEY_CURRENT_USER;
Win32Check( registry.OpenKey(registryPath, True) );
registry.WriteInteger(exeName, value)
finally
registry.Destroy();
end;
end;
Finaly add to your OnCreate of the Form:
TBrowserEmulationAdjuster.SetBrowserEmulationDWORD(TBrowserEmulationAdjuster.IE11_Quirks);
This should solve your problem

Calling a web service using the script tags

My application is built using asp classic and I've tried multiple solutions trying to fix IE 8's Service is not defined issue. The code is below.
tags:
<script language="javascript">
function init() {
service.useService("Services/Util.asmx?WSDL", "WebUtil");
}
</script>
tags:
<frameset onload="init()" id="service" style="behavior:url(Forms/Behaviors/webservice.htc)" onresult="ShowResult()" border="1" frameborder="1" framespacing="4" cols='<%= GetFrameColString()%>' topmargin="0" leftmargin="0">
Note:
The browser can not be updated due to company policy so it has to work in IE 8 and above. And if there are issues with later browsers when calling a webservice this way would help me out as well if the company decides to upgrade IE.
Anyhow can you help with IE 8's stating "service is not defined" issue?
Solved.
My original code:
<script language="javascript">
function init() {
service.useService("Services/Util.asmx?WSDL", "WebUtil");
}</script>
Modified code:
<script language="javascript">
function init() {
service.useService('Services/Util.asmx?WSDL', 'WebUtil');
}</script>
Apparently it's an syntax error. I assume ASP Classic needs single quotes over double quotes. Right now there is progress in getting my application done.

HOw can I use ExternalInterface from my Flash AS2 swf in an iFrame to call a javascript method?

I have a PHP script which includes a header file (header.php) which includes a javascript file containing some javascript methods.
ie -
Main.php =>
include("header.php");
// This page also embeds a swf in an iFrame (myFlash.swf)
header.php =>
<html>
<head>
<script type="text/javascript" src="javascript_methods.js"></script>
</head>
<body>
javascript_methods.js =>
myFunction() {
alert("function called");
}
myFlash.swf =>
import flash.external.ExternalInterface;
//When I want to call the javascript function myFunction() -
ExternalInterface.call("myFunction");
I have used ExternalInterface elesewhere in my app and (think) i did it the same way but the only difference is this time the swf is inside an iFrame so think this might be causing the problem. Is there a solution to making this communication to javascript from Flash through an iFrame, or is this not the issue and I have a problem somewhere else.
thanks
The argument passed to ExternalInterface.call will be evaled in the document where the flash is placed. This means that for this flash to reach the parent windows code, then it needs to do
ExternalInterface.call("window.parent.myFunction");

Categories

Resources