Flutter_web detect mouse hover and click in HtmlElementView - flutter-web

I am using flutter web to parse some website.
I need to detect the mouse hover and click inside a htmlElementView and then get the corresponded element. I tried to listen the onMouseUp() but it didn't work. can you give me advise?
Widget myfunc(){
ui.platformViewRegistry.registerViewFactory(
'my-html',
(int viewId) => IFrameElement()
..style.border = 'none'
..srcdoc = webData
..onMouseUp.listen((event) {
print('onMouseUp => $event');
})
..onSelect.listen((event) {
print('onSelect => $event');
})
..onMouseDown.listen((event) {
print('onMouseDown=> $event');
})
..onMouseEnter.listen((event) {
print('onMouseEnter => $event');
})
);
return HtmlElementView(
viewType:'my-html',
);
}
I plan to follow this post to extract the element, but it only work outside of htmlElementView().
How to get the selected text or the inner html in Dart

I don't find what is wrong but I use followed solution as an alternate.
I insert the JavaScript and listen to postMessage() on Dart side.
Step 1. add postMessage() in the HTML. I parse entire web HTML and insert the event.
var newElement = html.Element.html(element.outerHtml);
print('newElement=> ${newElement.outerHtml}');
newElement.attributes['onmouseover'] = 'window.parent.postMessage(this.id, \'*\')';
Step 2. Add the listener on the Dart side.
#override
void initState(){
super.initState();
html.window.onMessage.listen( listen);
}
void listen(dynamic event) {
print('listen...');
var data = (event as html.MessageEvent).data;
print(data);
}

Related

How to Scroll pdfView automatically with button click or volume buttons

I'm using barteksc pdf viewer library to load pdf in my application.
pdfView = findViewById(R.id.pdfView);
pdfView.fromAsset(getResources().getString(R.string.pdfname))
.enableDoubletap(true)
.enableSwipe(true)
.defaultPage(pageNumber)
.onPageChange(mainreading.this)
.pageFitPolicy(FitPolicy.WIDTH)
.pageFling(true)
.linkHandler(null)
.enableAnnotationRendering(true)
.swipeHorizontal(true)
.scrollHandle(new DefaultScrollHandlenew(mainreading.this))
.enableAntialiasing(true)
.load();
}
I want pdf to start scroll automatically when user click the button of volume up and down buttons to start stop. I tried with below code while wrapping it in the handler with handler.performClick(); but it shows blank screen while scrolling up and down.
scrollbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pdfView.scrollTo(0, pdfView.getScrollY() + 24);
}
});
Example :
https://play.google.com/store/apps/details?id=com.emptysheet.pdfreader_autoscroll&hl=en&gl=US
I want to make as like this. Can anyone help please.
Also tried with this. But it shows blank page after some scrolls.
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
if (action == KeyEvent.ACTION_DOWN) {
pdfView.scrollTo(0, pdfView.getScrollY() -24);
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (action == KeyEvent.ACTION_DOWN) {
pdfView.scrollTo(0, pdfView.getScrollY() + 24);
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}
You can simply use this PDF viewer from github.
It's based on the same 'barsteksc' pdf viewer with the feature to jump to any pages.
It's MagicalPdfViewer and you can use 'jumpTo(pageNo)' method to simply jump to the specific page. It also gives you the option to animate to the specific page with the same method, just pass 'true' as the 2nd parameter.
Moreover, if you pass the values like '-1' and 'bigger than pageNo', It will automatically scroll to the 0 & last page respectively.
Give it a try & let me know if you got what you wanted.

How do I disable the device back button on Android (react-native)?

How can I disable the physical device back button on Android with React-Native? I don't want to enable it for the user.
There is no out of the box support from React Native Navigation as of today on v2. However, you could use BackHandler from React native itself. To handle it and return false to disable it.
Doc on BackHandler
Example
BackHandler.addEventListener('hardwareBackPress', function() {
return false;
});
In activity you can override the onBackPressed() and comment the calling to super class.
#Override
public void onBackPressed() {
// super.onBackPressed(); comment this line to disable back button press
}
Current open screen is tracked with a listener created when the application is launched, in app.js. Main component of the app creates a BackHandler listener, which responds to the device back button according to the currently open screen.
Main component:
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.onBackPress);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.onBackPress);
}
onBackPress = () => {
if (this.props.currentScreen.name === 'app.main') {
Alert.alert(
'Confirm exit',
'Do you want to exit App?',
[
{text: 'CANCEL', style: 'cancel'},
{text: 'OK', onPress: () => {
BackHandler.exitApp()
}
}
]
);
} else {
Navigation.pop(this.props.currentScreen.id);
}
return true;
}
App.js
//register to compomentDidApperaListener to keep track on which screen is currently open. The componentName and Id are stored in my redux store
Navigation.events().registerComponentDidAppearListener(({ componentId, componentName }) => {
store.dispatch(updateCurrentScreen({'name': componentName, 'id': componentId}))
})

Xamarin.IOS UIBarbuttonItem added as in Recipe does not work. No error no button

Using Xamarin IOS app derived from The Tabbed Application template. Targeting IOS 11+; testing in simulator for 12.1.
I added a UINavigationBar to one of The UIView tabs and tried to add a save and cancel button into The bar.
No error, no joy, The NavigationItem is NOT null, and shows The correct Navigation Item. Here is The outline:
--UIViewController MyInfoController
----UIView InfoView
------UINavigationBar NavBar
--------UINavigationItem [no name]
------UIView ContentView
------A bunch of constraints
----UITabBar
and here is a relevant snippet of The code:
public partial class MyInfoController : UIViewController
{
protected MyInfoController(IntPtr handle) : base(handle)
{
// Note: this .ctor should not contain any initialization logic.
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Perform any additional setup after loading the view, typically from a nib.
this.NavigationItem.SetRightBarButtonItem(
new UIBarButtonItem(UIBarButtonSystemItem.Save, (sender, args) =>
{
// Handle Save Button Click here.
//Create Alert
var okAlertController = UIAlertController.Create("Click", "Right Button Clicked.", UIAlertControllerStyle.Alert);
//Add Action
okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
// Present Alert
PresentViewController(okAlertController, true, null);
}), true);
// Try another way...
var button = new UIBarButtonItem(UIBarButtonSystemItem.Cancel, (sender, e) =>
{
//Put Something here
});
button.SetTitleTextAttributes(new UITextAttributes()
{
TextColor = UIColor.White,
TextShadowColor = UIColor.Clear
}, UIControlState.Normal);
this.NavigationItem.SetLeftBarButtonItem(button, true);
// Create and add Views
No error messages issue. I don't see anything wrong, but I also don't see The bar button items.
What am I missing? (:-S)
If you use ios designer to add UINavigationBar and UINavigationItem ,you'd better set name for them ,like this
------UINavigationBar NavBar
--------UINavigationItem BarItem
So , in the controller , bar will show normally.
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Perform any additional setup after loading the view, typically from a nib.
this.BarItem.SetRightBarButtonItem(
new UIBarButtonItem(UIBarButtonSystemItem.Save, (sender, args) =>
{
// Handle Save Button Click here.
//Create Alert
var okAlertController = UIAlertController.Create("Click", "Right Button Clicked.", UIAlertControllerStyle.Alert);
//Add Action
okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
// Present Alert
PresentViewController(okAlertController, true, null);
}), true);
// Try another way...
var button = new UIBarButtonItem(UIBarButtonSystemItem.Cancel, (sender, e) =>
{
//Put Something here
});
button.SetTitleTextAttributes(new UITextAttributes()
{
TextColor = UIColor.Black,
TextShadowColor = UIColor.Clear
}, UIControlState.Normal);
this.BarItem.SetLeftBarButtonItem(button, true);
}
More info:
If you use this.NavigationItem ,this commonly used in root controller is UINavigationController .

Azure notification hub UWP, UWP toast notifications don't launch app

i'm using a notification hub for an UWP application following this tutorial : Getting started with Notification Hubs for Windows Universal Platform Apps.
If i test send with a Windows 8 notification like :
<?xml version="1.0" encoding="utf-8"?>
<toast>
<visual><binding template="ToastText01">
<text id="1">Test message</text>
</binding>
</visual>
</toast>
It works and if i click on the notification, it open the app through the OnLaunched() method. But if i send a UWP specific notification like :
<toast launch="app-defined-string">
<visual>
<binding template="ToastGeneric">
<text>Microsoft Company Store</text>
<text>New Halo game is back in stock!</text>
</binding>
</visual>
<actions>
<action activationType="foreground" content="See more details" arguments="details"/>
<action activationType="background" content="Remind me later" arguments="later"/>
</actions>
</toast>
The toast works but if I click on it, it open the app and OnLaunched() never called so the app stuck on spashscreen.
Thanks in advance for your help,
Regards
you need to implement OnActivated in your app.xaml.cs
protected override void OnActivated(IActivatedEventArgs args)
{
base.OnActivated(args);
}
see https://blogs.msdn.microsoft.com/tiles_and_toasts/2015/07/08/quickstart-sending-a-local-toast-notification-and-handling-activations-from-it-windows-10/
For those who have the same problem, with Dave Smits answer : juste add OnZctivated method in App.xaml.cs file and place same content as OnLaunched method :
protected override async void OnLaunched(LaunchActivatedEventArgs e)
{
await OnLaunchedOrActivated(e);
}
protected override async void OnActivated(IActivatedEventArgs e)
{
await OnLaunchedOrActivated(e);
}
private async Task OnLaunchedOrActivated(IActivatedEventArgs e)
{
// Initialize things like registering background task before the app is loaded
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
// TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
// Handle toast activation
if (e is ToastNotificationActivatedEventArgs)
{
var toastActivationArgs = e as ToastNotificationActivatedEventArgs;
// If empty args, no specific action (just launch the app)
if (toastActivationArgs.Argument.Length == 0)
{
if (rootFrame.Content == null)
rootFrame.Navigate(typeof(MainPage));
}
// Otherwise an action is provided
else
{
// Parse the query string
// See what action is being requested
// If we're loading the app for the first time, place the main page on the back stack
// so that user can go back after they've been navigated to the specific page
if (rootFrame.BackStack.Count == 0)
rootFrame.BackStack.Add(new PageStackEntry(typeof(MainPage), null, null));
}
}
// Handle launch activation
else if (e is LaunchActivatedEventArgs)
{
var launchActivationArgs = e as LaunchActivatedEventArgs;
// If launched with arguments (not a normal primary tile/applist launch)
if (launchActivationArgs.Arguments.Length > 0)
{
// TODO: Handle arguments for cases like launching from secondary Tile, so we navigate to the correct page
throw new NotImplementedException();
}
// Otherwise if launched normally
else
{
// If we're currently not on a page, navigate to the main page
if (rootFrame.Content == null)
rootFrame.Navigate(typeof(MainPage));
}
}
else
{
// TODO: Handle other types of activation
throw new NotImplementedException();
}
// Ensure the current window is active
Window.Current.Activate();
}

open a MVC4 view inside a jquery Dialog

I want to take a view and instead of opening a new page I want to just open that view inside a Jquery dialog. I was just wondering how it's done or if possible.
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Jquery_Dialog.Models;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
namespace Jquery_Dialog.Controllers
{
public class HomeController : Controller
{
private IEnumerable<Product> Products
{
get
{
return new List<Product>
{
new Product {ProductID = 1, Name = "Train", Category = "Toy", Price = 29.99M},
new Product {ProductID = 2, Name = "Truck", Category = "Toy", Price = 19.99M},
new Product {ProductID = 3, Name = "Bread", Category = "Food", Price = 2.49M},
new Product {ProductID = 4, Name = "Cookies", Category = "Food", Price = 2.99M}
};
}
}
public ActionResult Index()
{
IEnumerable<Product> productList = Products;
return View(productList);
}
public ActionResult Details(int id)
{
Product model = Products.Where(p => p.ProductID == id).SingleOrDefault();
return Request.IsAjaxRequest() ? PartialView(model) : PartialView(model);
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
Index.cshtml
#model IEnumerable<Jquery_Dialog.Models.Product>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css " />
<script src="http://code.jquery.com/jquery-1.8.2.js "></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js "></script>
<table> #foreach (var item in Model) {
<tr>
<td>
#Html.ActionLink(item.Name, "Details", new { id = item.ProductID }, new { #class = "ajax-details" })
</td>
</tr>
}
</table>
<div id="dialog" title="Title of dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
<script>
$(function () {
$('.ajax-details').on('click', function (e) { // bind to click event
// go get the page using the link's `href`
$.get($(this).prop('href'), function (response) {
$(response).dialog(); // take the response and throw it up in a dialog
// optional: Use jQuery UI's options to specify buttons and other
// settings here as well. It's also probably a good idea to
// bind the close event and $().remove() this element from
// the page on close since the user can click links over and
// over. (prevent DOM overload of hidden elements)
});
e.preventDefault(); // don't let it continue on
});
});
</script>
<script>
$("#dialog").dialog();
</script>
As you can see I have a simple dialog that opens a div but I want to be able to open the details view instead of clicking the ActionLink and going to a different page, I want to be able to click the ActionLink and have it open up in the dialog.
Assuming you make the ActionLink a little more accessible (by using a class name for instance):
#Html.ActionLink(item.Name, "Details", new { id = item.ProductID },
/* htmlAttributes: */ new { #class = "ajax-details" })
You also make a modification to the action so we can fetch partial contents when it's an ajax request:
public ActionResult Details(int id)
{
// this is another way of making sure that AJAX calls get partial content,
// but a normal visit would render the entire page.
return Request.IsAjaxRequest() ? PartialView(model) : View(model);
}
Optional You could also adjust your _ViewStart.cshtml file to do the same if this was common place on the website to render partial views/ajax supplementing:
#{
Layout = IsAjax ? null : "~/Views/Shared/_Layout.cshtml";
}
Now, we wire it up with AJAX. Again, reference the class name we game the link earlier (ajax-details):
$('.ajax-details').on('click',function(e){ // bind to click event
// go get the page using the link's `href`
$.get($(this).prop('href'), function(response){
$(response).dialog(); // take the response and throw it up in a dialog
// optional: Use jQuery UI's options to specify buttons and other
// settings here as well. It's also probably a good idea to
// bind the close event and $().remove() this element from
// the page on close since the user can click links over and
// over. (prevent DOM overload of hidden elements)
});
e.preventDefault(); // don't let it continue on
});
Don't have the opportunity to test it, but should get you in the ball park. if it doesn't get you close enough, let me know and I'll revisit the answer and adjust.

Resources