问题
I want to disable the default context menu that appears after a certain text is selected in iOS Safari (web browser). Is that possible?
回答1:
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
回答2:
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);
};
}
}();
}
回答3:
According to onclick blocks copy+paste on Mobile Safari?, if the text is in an element that has an onclick event, the context menu won't be displayed.
回答4:
Inspired by Hans Gustavson's answer, I propose a simpler solution in TypeScript:
function disableIosSafariCallout(this: Window, event: any) {
const s = this.getSelection();
if ((s?.rangeCount || 0) > 0) {
const r = s?.getRangeAt(0);
s?.removeAllRanges();
setTimeout(() => {
s?.addRange(r!);
}, 50);
}
}
document.ontouchend = disableIosSafariCallout.bind(window);
This solution is actually a workaround. When you select a text, you might still see the text selection callout shows and then disappear immediately. I am not sure whether Hans Gustavson's answer has the same defect...
来源:https://stackoverflow.com/questions/16039219/disable-selection-context-menu-in-ios-safari