pouya
pouya

Reputation: 3766

How to bind events to the rendition in epub.js

I want to register a right click listener on the page in epub.js but don't know how to do it. There is also passEvents method of rendition object but couldn't find any help on that either. This is my last try:

rendition.on("rendered", () => {
    const contents = rendition.getContents()
    contents.document.addEventListener('contextmenu', showContextMenu, false);
});

Upvotes: 2

Views: 2062

Answers (2)

ewulff
ewulff

Reputation: 2259

The following answer applies to "epubjs": "^0.3.88 which I'm using on a project where I want to completely disable user right click or user long press on every device.

When rendition is rendered, we get two parameters one of them being an iframe. If you inspect your reader you'll notice your epub file is being rendered inside an iframe. That's why adding the event listener to the main document of your application does not work.

After this you attach a contextmenu event to the iframe. This callback will return an event MouseEvent which you can cancel with event.preventDefault();. Then you could access the event rect properties to render anything in the location the user right-clicked. For this you could for example use event.clientX and event.clientY.

rendition.on('rendered', (rendition: Rendition, iframe: Window) => {
    helpers.log('Rendition rendered');
    iframe.document.documentElement.addEventListener('contextmenu', (event: MouseEvent) => {
        helpers.log('Stopping contextual menu coming from epubjs iframe');
        event.preventDefault();
    });
});

Hope this helps to anyone working with epubjs in 2021.

Upvotes: 1

trinaldi
trinaldi

Reputation: 2950

Based on what you asked and I hope I got it right, you want a contextmenu event at the book itself, right?

If that's the case I used the following JS:

rendition.on("rendered", (e,i) => {;
  i.document.documentElement.addEventListener('contextmenu', (cfiRange, contents) => {
      console.log('hey');
  })
});

This code simply returns hey when I right click at the book. But as you can see there are two parameters (cfiRange, contents) which contains what you need.

In any case, I created a fiddle.

Another solution would be use document as the element receiving the event, but in my tests it gets everything but the book.

Upvotes: 2

Related Questions