I am able to call java from javascript on click of Button. But the same function is not getting invoked on document.ready
Here is my code
This is the index.html inside asset
<!DOCTYPE >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function init()
{
var testVal = 'Привет от Android Tools!';
AndroidFunction.showToast(testVal);
}
$(document).ready(function() {
//$('form').submit();
init();
});
</script>
</head>
<body>
<div style="clear: both;height: 3px;"> </div>
<div>
<input value="submit" type="button" name="submit"
id="btnSubmit" onclick="javascript:return init();" />
</div>
</body>
</html>
This is the kotlin code
class JavaScriptInterface internal constructor(c: Context) {
var mContext: Context
#JavascriptInterface
fun showToast(toast: String?) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show()
}
private fun callDummyPage(webView : WebView){
val webSettings: WebSettings = webView.getSettings()
webSettings.javaScriptEnabled = true
webView.webViewClient = MyWebViewClient()
webView.webChromeClient = MyWebChromeClient()
webView.addJavascriptInterface(JavaScriptInterface(activity!!.baseContext), "AndroidFunction");
webView.loadUrl("file:///android_asset/index.html");
}
init {
mContext = c
}
}
ready() is a jQuery method and you are not importing the library. You can try importing the library at your scripts adding <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> on your <head> ... </head>
You can also change your function to plain Vanilla Js
document.addEventListener("DOMContentLoaded", function(event) {
// Your code to run since DOM is loaded AND ready
});
Related
I am using CEFSharp in WPF app.
Currently i am loading local html file in chromium based browser.
xaml
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Name="buttonTest" Content="Click me" Grid.Row="0" Width="50px" Height="30px" Click="buttonTest_Click" />
<!--<WebBrowser Name="webBrowser" Grid.Row="1" />-->
<!--<WebBrowser Name="webBrowser" Grid.Row="1" />-->
<wpf:ChromiumWebBrowser x:Name="webBrowser" Grid.Row="1"/>
</Grid>
cs
BrowserSettings browserSettings = new BrowserSettings();
browserSettings.FileAccessFromFileUrls = CefState.Enabled;
browserSettings.Javascript = CefState.Enabled;
browserSettings.UniversalAccessFromFileUrls = CefState.Enabled;
webBrowser.BrowserSettings = browserSettings;
webBrowser.Address = "file:///" + path;
Loading html is working completely fine.
Now i am trying to call javascript function on a click of WPF Button.
private async void buttonTest_Click(object sender, RoutedEventArgs e)
{
try
{
if (webBrowser.IsBrowserInitialized)
{
var task = await webBrowser.EvaluateScriptAsync("document.body.style.background = 'red';");
var task1 = await webBrowser.EvaluateScriptAsync("startInterval()", new Object { });
//webBrowser.ExecuteScriptAsync("alert(2 + 2);");
}
//webBrowser.InvokeScript("startInterval");
}
catch (Exception ex)
{
}
}
html page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="css/site.css" />
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.bundle.min.js"></script>
<script src="js/site.js"></script>
<script type="text/javascript">
$(function () {
'use strict';
function startInterval() {
alert("qqf5");
}
function clearInterval() {
}
$("#buttonGetData").click(function () {
startInterval();
});
});
</script>
</head>
<body>
<div class="container">
<main role="main" class="pb-3">
<button type="button" id="buttonGetData">Get Data!</button>
</main>
</div>
</body>
</html>
From wpf if i click on button then page background color is changed but method is not called.
But if i click on from html page then it it working fine.
What i am missing here?
I want to develop an application that will display sensor data in both windows8 and android.
I'm using phoneGap for some sensors, but, for example, barometer, there is no implementation in phoneGAP.
I want to develop a plugin for cordova-windows8. but there is no example in the web for how to do it.
I want to call c# function that uses Microsoft.codePack API for sensors in order to display the barometer data.
the ApiCodePack uses windows 7 API for sensors.
http://archive.msdn.microsoft.com/WindowsAPICodePack
is there any option to develop a plugin for cordova-windows8 that will call c# code?
a sample application will be appreciate.
thanks!
Yes of course you can call C# code in phone gap
You need to refer Plugin development Guide
sample plugin for calculator
HTML CODE :calculator.html
<html>
<head>
<!-- meta name="viewport" content="width=device-width, height=device-height, user-scalable=yes, initial-scale=2.0, maximum-scale=4.0, minimum-scale=1.0" / -->
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/> <!-- ISO-8859-1 -->
<title>Cordova</title>
<link rel="stylesheet" href="master.css" type="text/css" media="screen"/>
<script type="text/javascript" charset="utf-8" src="cordova-current.js"></script>
<script type="text/javascript" charset="utf-8">
var deviceReady = false;
/**
* Function called when page has finished loading.
*/
function init() {
document.addEventListener("deviceready", function () {
deviceReady = true;
console.log("Device=" + device.platform + " " + device.version);
}, false);
window.setTimeout(function () {
if (!deviceReady) {
alert("Error: Cordova did not initialize. Demo will not run correctly.");
}
}, 1000);
}
function calculateSum() {
cordova.exec(
function (res) {
document.getElementById('res').innerHTML = res;
},
function (e) {
console.log("Error occurred: " + e);
document.getElementById('res').innerHTML = "Error occurred: " + e;
},
"Calculator", "sum",
{ x: document.getElementById('x').value, y: document.getElementById('y').value });
};
</script>
</head>
<body onLoad="init();" id="stage" class="theme">
<h1>Calculator</h1>
<div id="info">
<span class='tb-label'>X</span> <span id="Span1"></span>
<input type="text" id="x" value="1" style="width:250px;height:20px;"/>
<br/>
<span class='tb-label'>Y</span> <span id="Span2"></span>
<input type="text" id="y" value="2" style="width:250px;height:20px;"/>
<br/>
Sum: <span id="res"></span>
</div>
<h2>Action</h2>
<a class="btn large" onclick="calculateSum();">Calculate</a>
<h2> </h2>Back
</body>
</html>
C# Code :calculator.cs
using System.Runtime.Serialization;
using WPCordovaClassLib.Cordova;
using WPCordovaClassLib.Cordova.Commands;
using WPCordovaClassLib.Cordova.JSON;
namespace Cordova.Extension.Commands
{
public class Calculator : BaseCommand
{
[DataContract]
public class CalculateParameters
{
[DataMember]
public double x { get; set; }
[DataMember]
public double y { get; set; }
}
public void sum(string args)
{
CalculateParameters calcParam = JsonHelper.Deserialize<CalculateParameters> (args);
this.DispatchCommandResult(new PluginResult(PluginResult.Status.OK, calcParam.x + calcParam.y));
}
}
}
enjoy custom plugin for c#
i am trying to get html string from my site as it presented in browser
firstly i tried to use web client
using (var client = new WebClient())
{
var content = client.DownloadString("my_site_address");
}
but in my site i have some javascript code that change the view (and webClient does not run javascript)
so i use wpf WebBrowser and after nevigate to the desire site it show the page (as expected) but when i try to get the html string it show just like the webClient
dynamic doc = MainBrowser.Document;
var htmlText = doc.documentElement.InnerHtml;
this is how i get the html:
<!DOCTYPE html>
<head>
<title>Title</title>
</head>
<body>
<div class="conteiner">
<div class="matrix">
<script type="text/javascript">
// some script code
</script>
<script type="text/javascript" src="xxx"></script>
Matrix
</div>
<div class="zoom">
Zoom
</div>
</div>
<div class="test">
<script type="text/javascript">
// some script code
</script>
<script type="text/javascript" src"xxx2"></script>
</div>
</body>
</html>
and this is how i should get it after the javascript change it:
<html><head>
<title>Title</title>
</head>
<body>
<div class="conteiner">
<div class="matrix">
<script type="text/javascript">
</script>
<script type="text/javascript" src="xxx"></script><iframe ></iframe><script ></script><div ><div ><iframe >
<html><head>
<title></title>
</head>
<body>
<div >
<ul><li><ol><li <a </a></li></ol></li></ul> </div>
</body></html>
</iframe></div></div></div>
Matrix
</div>
<div class="zoom">
Zoom
</div>
</div>
<div class="test">
<script type="text/javascript">
</script>
<script type="text/javascript" src="xxx2"></script><div ><div ><div ><iframe ></iframe></div></div></div>
</div>
</body></html>
Please help :)
You can use the WebDriver framework from Selenium. It offers different web driver implementations, like for Internet Explorer or Firefox.
Here is some sample code to request a web site with Internet Explorer, let it render and finally save the final HTML markup.
public class WebSiteHtmlLoader : IDisposable
{
private readonly RemoteWebDriver _remoteWebDriver;
public WebSiteHtmlLoader(RemoteWebDriver remoteWebDriver)
{
if (remoteWebDriver == null) throw new ArgumentNullException("remoteWebDriver");
_remoteWebDriver = remoteWebDriver;
}
public string GetRenderedHtml(Uri webSiteUri)
{
if (webSiteUri == null) throw new ArgumentNullException("webSiteUri");
_remoteWebDriver.Navigate().GoToUrl(webSiteUri);
return _remoteWebDriver.PageSource;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (_remoteWebDriver != null)
{
_remoteWebDriver.Quit();
}
}
}
}
Usage:
class Program
{
static void Main(string[] args)
{
if (!args.Any())
{
return;
}
var pageUrl = args.First();
var options = new InternetExplorerOptions
{
IntroduceInstabilityByIgnoringProtectedModeSettings = true,
PageLoadStrategy = InternetExplorerPageLoadStrategy.Eager
};
using (var htmlLoader = new WebSiteHtmlLoader(new InternetExplorerDriver(options)))
{
var html = htmlLoader.GetRenderedHtml(new Uri(pageUrl, UriKind.Absolute));
File.WriteAllText(#"C:\htmlloadertext.html", html);
}
}
}
You could try to use the WebBrowser.DocumentText property. Like, add a hidden WebBrowser control to your application and call Navigate() function, then call the property to get the generated HTML
More info at: http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.documenttext.aspx
i'm having problem in passing data/variable from android to javascript.here is my code.
WebView webview = (WebView) findViewById(R.id.webview_graph);
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
String temp = "yoolod";
webview.loadUrl("file:///android_asset/test.html");
webview.loadUrl("javascript:sample(\""+temp+"\")");
in test.html
<!DOCTYPE html>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
function sample(var){ //this is line 10
document.write (var);
//echo var;
}
</script>
</head>
<body>
</body>
</html>
I always have this, error and can't find solution yet. Hope you can help me.
"Uncaught ReferenceError: sample is not defined", source: (1)
"Uncaught SyntaxError: Unexpected token var", source: file:///android_asset/test.html (10)
after searching and trial error i somehow found a way. i just put the loadurl where im calling the function inside the onfinished of the webview.
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String loc) {
view.loadUrl("javascript:sample('"+temp+"')");
}
});
Put the value in to the single quotes, below i have changed your code, take that code and try again.
webview.loadUrl("javascript:sample('"+temp+"')");
i have set the value (which is getting from the android) in edittext.
so you will get value in to the edit text in html.
test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width; user-scalable=0;" />
<script language="javascript">
// getting Value from Android/ios
function sample(temp){
var textcontrol = document.getElementById("txtname");
textcontrol.value = temp;
}
</script>
<title>My HTML</title>
</head>
<body >
<h1>My HTML </h1>
<br>
<input type="text" id="txtname" />
</body>
</html>
I have the code that I have posted below in my webpage. As you can see it uses the body onload function to launch the script. Is there any way of making this script work without this and in JavaScript instead?
<!doctype html>
<html>
<head>
<script type="text/javascript">
function box(query){
return document.getElementById(query)
}
</script>
</head>
<body onload="box('query').focus();">
<input id="query" type="text">
</body>
</html>
Thanks in advance,
Callum
This might what you're looking for: Attach a body onload event with JS
I'd suggest using jQuery or some other JavaScript framework unless you're exploring JS or have some stringent restrictions on using libraries and frameworks.
the following code helpful for you
this is jquery:
$(document).ready(function(){
function name();
});
or
$(window).load(function(){
function name();
});
the following answers using javascript:
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function load() {
alert('function loaded');
}
window.onload = load;
</script>
</head>
<body>
</body>
</html
----------
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function load() {
alert('function loaded');
}
</script>
</head>
<body onload="load();">
</body>
</html
if you are talking about catching the onload event with writting any javascript in your html you can use this function:
// Add event
var addEvent = function (obj, evType, fn){
if (obj.addEventListener){
obj.addEventListener(evType, fn, false);
return true;
}else if (obj.attachEvent){
var r = obj.attachEvent("on"+evType, fn);
return r;
} else {
return false;
}
};
Now you can run all the functions you need in your onload event.
addEvent(window,'load',function () {
box('query').focus();
// or
document.getElementById('query').focus();
});