UWP Webview ScriptNotify is not getting trigerred - javascript

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.

Related

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

How do i remote include a javascript file in Titanium appcelerator and use the functions of that file?

I am required to remotely include into my appcelerator project, a javascript file available at a particular link, and use the function declared in that file to process some data.
What i would like to achieve is something like the following in html -
<script src="https://some-link/Data.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var testVariable = someMethod(localdata);
});
//use testVariable as necessary
</script>
//someMethod() is declared in remotely available Data.js
I am a newb at Appcelerator and im not really able to follow some of the threads i have come across, so some detailed help would be really appreciated. Thank you in advance.
Well according to me , you should first understand few points first :
You want to include a remote file hosted at some server , now as the Titanium code converts to native code at compile time , you cannot include Titanium API's from remote file.
If you want to include a remote file , then only option which I see is loading that file in webview.
Now coming to your problem , as you said that you want to fetch some data only from remote server by triggering some JS function from remote file. So following is what would I do :-
a/ Create a hidden webview in my main window with a EventListener of webview. Something like :
var webview = Titanium.UI.createWebView({url:'localHtmlFile.html'});
//event listener to handle the response from webview
Ti.App.addEventListener('fromWebView', function(e)
{
var testVariable = e.data;
});
b/ In localHtmlFile.html file :
<!DOCTYPE html>
<html>
<body>
<script src="https://some-link/Data.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var testVariable = someMethod();
//respond the fetch data to the main window via fireEvent
Ti.App.fireEvent( 'fromWebView', { data : testVariable } );
});
</script>
</body>
</html>
PS : This is just a logic to begin with , you have to edit code according to your requirements

Loading javascript functions to webview in Android Kitkat

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.

Flashdevelop issue with publishing

I have created a simple flash object to redirect a browser to a different webpage using "navigatetoURL" while getting the URL from externalinterface calls to the javascript that the page doing the embedding of the flash file has.
I am able to build everything just fine and the html page I created (using swfobject.embedSWF to embed the flash file) runs fine and redirects the browser. However when I move the files that are needed for everything to function (the .swf file, swfobject.js, and the html file that embeds the flash object) the webpage does not redirect anymore. Just a blank space, which seems to be the flash object, is displayed and nothing is redirected.
Is there any compile option in Flashdevelop that I'm missing to prevent correct this?
Here is the actionscript 3 code:
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.net.navigateToURL;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.external.ExternalInterface;
public class FlashTest extends Sprite
{
public function FlashTest()
{
var url:String = ExternalInterface.call("GetURL");
var hash:String = ExternalInterface.call("GetHash");
var new_url:String = url + hash;
var request:URLRequest = new URLRequest(new_url);
navigateToURL(request, "_self");
}
}
}
The HTML code:
<html>
<head>
<script src='js/swfobject.js' type='text/javascript'></script>
<script type='text/javascript'>
swfobject.embedSWF('Flashtest.swf', 'altContent', '100%', '100%', '10.0.0');
function GetURL()
{
return 'http://www.cnn.com';
}
function GetHash()
{
return '?hash=2398asb9s8234';
}
</script>
</head>
<body>
<div id='altContent'>
<h1>Flash_test</h1>
<p>Alternative content</p>
<p><a href='http://www.adobe.com/go/getflashplayer'><img
src='http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif'
alt='Get Adobe Flash player' /></a></p>
</div>
</body>
</html>
Actually, I've been in trouble with swf's being started before they are added to the HTML DOM and/or before the DOM is ready. Have a look at Adobes own article on ExternalInterface.call and javascript isReady.
I would also have a look at the allowScriptAccess parameter:
<script type="text/javascript">
var so = new SWFObject("movie.swf", "mymovie", "400", "200", "8", "#336699");
so.addVariable("allowScriptAccess", "always");
so.write("flashcontent");
</script>
It's actually a flash player security issue. If you move the files out of the bin folder and run them local they won't work any more.
Each time you create a project in flashdevelop the "bin" folder is added to the exception list of the flash player.
If you move the files to another folder then they won't work anymore hence the blank page when opening the html in browser.
The solution is to manually modify the flash player security config file and add the new path or to visit:
http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html
Click on Global Security Settings > Always Allow > Edit ocations > Add Location > Browse for the new path, where the files are located.

Categories

Resources