Add a custom context menu in a WebView

by mandel on February 13th, 2012

Yesterday I was working on a small UI that uses a WebKit.WebView to show certain information to the user. My idea yesterday was to try and show a native context menu on the view that does not have the default menu items that the WebView has, the only way I’ve found to this is a as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from gi.repository import GObject, Gdk, Gtk, WebKit
from utils import get_data_file
 
 
class CustomView(Gtk.EventBox):
    """Main window used to show the ui and generate signals."""
 
    def __init__(self):
        """Create a new instance."""
        super(CustomView, self).__init__()
        self.set_events(Gdk.EventMask.BUTTON_PRESS_MASK)
        self._create_context_menu()
        self.scroll = Gtk.ScrolledWindow()
        self.scroll.show()
        self.view = WebKit.WebView()
        self.view.show()
        self.scroll.add(self.view)
        # load the html used for the main window, from that point
        # on we will let the html and js do the work and raise
        # signals via the title
        self.view.open(get_data_file(MAIN_WINDOW_HMTL))
        # lets no use the webkit context menu
        settings = self.view.get_settings()
        settings.set_property('enable-default-context-menu',
                              False)
        self.view.set_settings(settings)
        self.add(self.scroll)
        # connect the on button pressed event of the event box
        # so that we can add a context menu
        self.connect('button_press_event', self._on_button_press_event)
 
    def _create_context_menu(self):
        """Create the context menu."""
        self.menu = Gtk.Menu()
        delete_menu = Gtk.MenuItem("Delete Task")
        self.menu.append(delete_menu)
 
    def _on_button_press_event(self, widget, event):
        """Deal with the button press event."""
        if event.button == 3:
            self.menu.popup(None, None, None, None, event.button, event.time)
            self.menu.show_all()

Does any one out there know a better way to do this. I know that there is a “populate-popup” signal I can listen to but I cannot get my head around on how to do exactly what I want, which is remove all defaul menu items and add my own. And, does it make sense to have to do that for every popup signal?