Search code examples
c#silverlightwindows-phone-7silverlight-toolkit

how to add context menu to WebBrowser wp7?


Is it possible to add Context Menu to WebBrowser in WP7?(like IE)

silverlight toolkit Context Menu not support WebBrowser!!!


Solution

  • The WebBrowser does not support context menus and doesn't function like other Silverlight controls. Therefore, it's not possible to directly add a ContextMenu. However, there are workarounds possible. One of them is to use the InvokeScript method. You should read this thread. Apparently the code at the bottom of the thread works. Note: GINternet is the WebBrowser control's name, so you'll need to change that to yours.

    public void AttachContextMenu()
    {
          try
          {
               if (GINternet.IsScriptEnabled)
               {
                    GINternet.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}");
                    GINternet.InvokeScript("execScript", "document.oncontextmenu = HandleContextMenu;");
               }
          }
          catch
          {
          }
    }