How to design a right click menu in Webview for any website?
There is oncontextmenu
event in html that use to detect right click. And you could use WebView
InvokeScriptAsync
to inject detected method to eval function where in the html page. And when right click fired, you could use window.external.notify
call back.
For example
Create right click menu for <a>
tag.
public MainPage()
{
this.InitializeComponent();
MyWebView.LoadCompleted += MyWebView_LoadCompleted;
}
private async void MyWebView_LoadCompleted(object sender, NavigationEventArgs e)
{
string functionString = @"var anchors = document.querySelectorAll('a');
for (var i = 0; i < anchors.length; i += 1) {
anchors[i].oncontextmenu = function (e) {
var e = e||window.event;
var oX = e.clientX;
var oY = e.clientY;
var href = this.getAttribute('href');
window.external.notify([oX.toString(), oY.toString(), href].toString());
};
}";
await MyWebView.InvokeScriptAsync("eval", new string[] { functionString });
}
private void MyWebView_ScriptNotify(object sender, NotifyEventArgs e)
{
var items = e.Value.Split(',');
MenuFlyout myFlyout = new MenuFlyout();
MenuFlyoutItem firstItem = new MenuFlyoutItem { Text = "Open new tab" };
myFlyout.Items.Add(firstItem);
myFlyout.ShowAt(sender as UIElement, new Point(System.Convert.ToDouble(items[0]) , System.Convert.ToDouble(items[1])));
}
Please note
Allowed sites are specified in the Content URIs section of Package.appxmanifest and cannot contain domain wildcards and must be https .

And this is code sample that you could refer.