Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable selection context menu in iOS safari

I want to disable the default context menu that appears after a certain text is selected in iOS Safari (web browser). Is that possible?

context menu destroy

like image 669
Samin Avatar asked Oct 05 '22 09:10

Samin


2 Answers

It is possible, see this example. Basically, the important part is to set the right css atributes:

body { -webkit-touch-callout: none !important; }
a { -webkit-user-select: none !important; }

Also, here is a question which solves a similar issue

like image 130
Daniel Avatar answered Oct 10 '22 05:10

Daniel


The only way i found was by removing the selection and select again with javascript. Have a look at my code:

/* prevent ios edit-menu */
if (/(iPad|iPhone|iPod)/g.test(navigator.userAgent)) {
    !function(){
        var target = document.body; // the element where the edit menue should be disabled

        var preventSelRecursion;
        document.addEventListener('selectionchange', function(e){
            var S = getSelection();
            if (!S.rangeCount) return;
            if (S.isCollapsed) return;
            var r = S.getRangeAt(0);
            if (!target.contains(r.commonAncestorContainer)) return;
            if (preventSelRecursion) return;
            iosSelMenuPrevent();
        }, false);

        var iosSelMenuPrevent = debounce(function(){
            var S = getSelection();
            var r = S.getRangeAt(0);
            preventSelRecursion = true;
            S = getSelection();
            S.removeAllRanges();
            setTimeout(function(){ // make remove-add-selection removes the menu
                S.addRange(r);
                setTimeout(function(){
                    preventSelRecursion = false;
                });
            },4);
        },800); // if no selectionchange during 800ms : remove the menu

        /* helper-function */
        function debounce(fn, delay) {
            var timer = null;
            return function () {
                var context = this, args = arguments;
                clearTimeout(timer);
                timer = setTimeout(function () {
                    fn.apply(context, args);
                }, delay);
            };
        }
    }();
}
like image 37
Hans Gustavson Avatar answered Oct 10 '22 04:10

Hans Gustavson