i successfully added a contextmenu to my webbrowser with this javascript code:
public void AttachContextMenu()
{
try
{
if ((App.Current as App).Browser.IsScriptEnabled)
{
(App.Current as App).Browser.InvokeScript("execScript", "function FindParentLink(item) \r\n{\r\n\tif (!item.parentNode)\r\n\t\treturn null;\r\n\tif (item.tagName.toLowerCase() == 'a') \r\n\t{\r\n\t\treturn item;\r\n\t} \r\n\telse \r\n\t{\r\n\t\treturn FindParentLink(item.parentNode);\r\n\t}\r\n}\r\n\r\nfunction FindParentImage(item) \r\n{\r\n\tif (!item.parentNode)\r\n\t\treturn null;\r\n\tif (item.tagName.toLowerCase() == 'img') \r\n\t{\r\n\t\treturn item;\r\n\t} \r\n\telse \r\n\t{\r\n\t\treturn FindParentImage(item.parentNode);\r\n\t}\r\n}\r\n\r\nfunction HandleContextMenu() \r\n{\r\n\tvar linkItem = FindParentLink(event.srcElement);\r\n var imageItem = FindParentImage(event.srcElement);\r\n var notifyOutput = '';\r\n if (linkItem != null) if (linkItem.href != null) notifyOutput += linkItem.href;\r\n if (imageItem != null) if (imageItem.src != null) notifyOutput += imageItem.src;\r\n if (notifyOutput != '')\r\n window.external.notify(notifyOutput);\r\n else\r\n\t\twindow.external.notify('NOTLINKIMG');\r\n}");
(App.Current as App).Browser.InvokeScript("execScript", "document.oncontextmenu = HandleContextMenu;");
}
}
catch
{
}
}
this method is used everytime the browser navigated.
So, the scriptnotify code, which will be used when the user holds a link :
if (e.Value.ToString() != null && IsValidUri(e.Value.ToString()))
{
ContextMenu cm = new ContextMenu();
MenuItem menuItem0 = new MenuItem() { Header = "X", Tag = e.Value };
menuItem0.Click += new RoutedEventHandler(X_Click);
MenuItem menuItem1 = new MenuItem() { Header = "Y", Tag = e.Value };
menuItem1.Click += new RoutedEventHandler(Y_Click);
MenuItem menuItem2 = new MenuItem() { Header = "Z", Tag = e.Value };
menuItem2.Click += new RoutedEventHandler(Z_Click);
cm.Items.Add(menuItem0);
cm.Items.Add(menuItem1);
cm.Items.Add(menuItem2);
ContextMenuService.SetContextMenu(Browser, cm);
cm.IsZoomEnabled = false;
cm.VerticalOffset = mouseClickPosition.Y;
cm.IsOpen = true;
}
so far, i hope i made everything right.
now, it randomly works. nearly 50% of tries cause a error, Visual studio navigates to a blue-white frame named “No source available” and throws a NullReferenceException.
Where should this be solved? already set a try-catch block around the hole 2 method, no change :/
hope you have some ideas
greets
roqstr
don’t got it working, but there’s a workaround:
AttachContextMenu()
-> holding a link will push the url to the scriptnotify method.
build a custom contextmenu & everything is fine.