Add a custom context menu

This sample shows how to add a custom context menu to the viewer. The custom menu created in the sample code is displayed instead of the standard one only if some text is selected in the PDF, and allows the user to search for the selected text using either Google or Bing.

window.onload = function() { //DsPdfViewer.LicenseKey = "***key***"; const options = { workerSrc: "/document-solutions/javascript-pdf-viewer/demos/product-bundles/build/dspdfviewer.worker.js", onBeforeOpenContextMenu: function (items, mousePosition, viewer) { // Modify context menu: var selectedText = viewer.getSelectedText(); if (selectedText) { // Remove existent items: items.splice(0, items.length); // Add own menu items: items.push({ type: 'button', text: 'Search using Google', onClick: function () { window.open('http://www.google.com/search?q=' + encodeURI(selectedText), '_blank'); } }); items.push({ type: 'button', text: 'Search using Bing', onClick: function () { window.open('https://www.bing.com/search?q=' + encodeURI(selectedText), '_blank'); } }); } return true; }, restoreViewStateOnLoad: false }; const viewer = new DsPdfViewer("#viewer", options); viewer.addDefaultPanels(); viewer.mouseMode = 0;/* MouseMode.Select */ viewer.open("/document-solutions/javascript-pdf-viewer/demos/product-bundles/assets/pdf/how-to-choose-js-framework.pdf"); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Custom Context Menu</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./src/styles.css"> <script src="/document-solutions/javascript-pdf-viewer/demos/product-bundles/build/dspdfviewer.js"></script> <script src="/document-solutions/javascript-pdf-viewer/demos/product-bundles/build/wasmSupportApi.js"></script> <script src="/document-solutions/javascript-pdf-viewer/demos/resource/js/init.js"></script> <script src="./src/app.js"></script> </head> <body> <div id="viewer"></div> </body> </html>
#viewer { height: 100%; }