Preventing Copy and Paste function in WKWebView - A Guide

I am seeking a solution to deactivate the callout menu that appears when an element is long-tapped in a web view:

https://i.sstatic.net/TiWsY.png

Despite various answers available, like this one, none seem to be effective. It's unclear whether the techniques for UIWebView are also applicable to WKWebView ...

I attempted to manipulate the CSS using JavaScript. However, this only seems to work if scripts are added to the WKUserContentController and not within didFinish().

The following methods do not produce desired outcomes:

window.getSelection().removeAllRanges();
document.body.style.webkitTouchCallout='none';
document.body.style.webkitUserSelect='none';

Some partially successful approaches include:

var style = document.createElement('style');
style.innerHTML = '* { -webkit-touch-callout: none; -webkit-user-select: none; }';
document.getElementsByTagName('head')[0].appendChild(style);

Alternatively, in CSS form:

*:not(input):not(textarea) {
    -webkit-user-select: none;    /* disable selection/copy of UIWebView */
    -webkit-touch-callout: none;  /* disable the iOS popup when long-press on a link */
}

Only wildcard selector * or *:not(input):not(textarea) appear to be effective (not specific tags like body). Unfortunately, these methods disable many elements indiscriminately ... I require this functionality on specific elements only!

I also experimented with canPerformAction():

private static readonly Selector copyAction = new Selector("copy:");
private static readonly Selector pasteAction = new Selector("paste:");
private static readonly Selector cutAction = new Selector("cut:");

public override bool CanPerform(Selector action, NSObject withSender)
{
    if (action == copyAction || action == pasteAction || action == cutAction)
    {
        System.Diagnostics.Debug.WriteLine(action.Name);
    }

    return false;
}

In this case, it appears that another responder in the chain is overriding my settings by returning true. The popup/menu continues to appear. My efforts have only been able to limit the available options (as shown in the screenshot).

My next thought is to utilize gesture recognizers to prevent such taps, although I lack knowledge in this area at present.

What steps can I take to successfully disable the popup/callout menu?

Answer №1

While I was able to successfully override the canPerformAction method in UIWebView, I encountered difficulties when trying to do the same in WKWebView.

    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    if action == #selector(UIResponderStandardEditActions.cut(_:)) ||
        action == #selector(UIResponderStandardEditActions.copy(_:)) ||
        action == #selector(UIResponderStandardEditActions.selectAll(_:)) ||
        action == #selector(UIResponderStandardEditActions.select(_:)) {
        return false
    }
    return super.canPerformAction(action, withSender: sender)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to maintain global position, rotation, and scale when adding an object to a group in Three.js

I need to transfer an object from one group (or world/scene) to another group while maintaining its global transformation. I want the object to appear unchanged. Here is an example of what I am trying to achieve: //store the current world transformation ...

Angular Igx-calendar User Interface Component

I need assistance with implementing a form that includes a calendar for users to select specific dates. Below is the code snippet: Here is the HTML component file (about.component.html): <form [formGroup]="angForm" class="form-element"> <d ...

"Caution: Refs cannot be assigned to function components" message encountered when utilizing a custom component in Next.js

I created a component called HeaderIcon with the following code: function HeaderIcon({ inactiveIcon, activeIcon }) { const [isActive, setIsActive] = useState(false); return ( <div onClick={() => setIsActive(!isActive)}> {isActive ? ...

Scrolling is disabled on mobile devices

One issue I am encountering with my website is related to scrolling on mobile devices. Sometimes, the website freezes when trying to scroll, and even swiping a finger across the device does not move the website properly. However, scrolling works fine on de ...

Discover the process of gathering and storing data on UITableView button presses

I could use some assistance with my Table View app. I have a .plist file containing information about continents, countries, and other data. I am working with a Storyboard and have set up 3 View Controllers (MasterVC - for continents, MiddleVC - for count ...

The setInterval timer is malfunctioning within the render() method of ReactJS

In my React component, I have a countdown timer that starts at 10 seconds. If the backend data is received within this time frame, the timer stops. If not, it will continue counting down to 0 and then refresh the page, repeating the cycle until the data is ...

Turn off scrolling for the body content without removing the scrollbar visibility

Whenever I click a thumbnail, a div overlay box appears on top: .view-overlay { display:none; position:fixed; top:0; left:0; right:0; bottom:0; overflow-y:scroll; background-color:rgba(0,0,0,0.7); z-index:999; } Some browsers with non-f ...

Tips for centering or aligning a component to the right using Material UI?

Is there an efficient method to align my button to the right of its parent in Material UI? One approach could be using: <Grid container justify="flex-end"> However, this would also require implementing another <Grid item />, which m ...

What is the best way to retrieve data from an Express endpoint within a React component?

I am working on integrating a React component with an Express endpoint that returns the string "sample data". The goal is to call this endpoint from my React app, store the text in state, and then display it on the screen. Here is my component: class App ...

"Menu bar showcasing various products and services in the

Is there a way to design a menu similar to the one on this website using bootstrap 4? https://i.sstatic.net/2wkck.jpg The menu layout features categories on the sidebar and collapses in mobile view. How can I achieve this with bootstrap 4? ...

Can the discriminator be preprocessed in a zod discriminated union?

Is it possible to convert string formatted numbers to numbers before using a value in z.discriminatedUnion? Here is an example code snippet: import { z } from "zod"; const BrushColorEnum = z.enum( ["BLUE_SILVER", "GREEN_SILVER&q ...

Mastering state management for various input types in React

Developing a proof of concept for showcasing tennis player details on a webpage. The page can display information for any number of players, and the user should be able to update all player details simultaneously. I have created 3 components: PlayersPage, ...

Is it possible to verify the presence of data in a database using the ajax method?

This piece of JavaScript code is responsible for validating mobile number data, among other information, and sending it to validate_user.php for storage. However, I only want to store the data of users whose mobile numbers exist in another table; otherwise ...

Pins missing from Google Maps API display

TLDR: The problem lies within the var marker = new google.maps.Marker() line. It seems that either the pins are not visible, incorrect, or simply not appearing. Background: I have implemented some JavaScript code that utilizes AJAX to fetch data on the ...

In JavaScript, select a specific date and automatically set another date that is exactly 3 months in the future

I would greatly appreciate some suggestions and any helpful links pertaining to my query. As a newcomer in JavaScript, I am unsure of where to begin. //JavaScript code snippet ...

Retrieve the HTML tags following the modification of my information in ASP.NET

Apologies for any language errors, I am new to asp.net development. 1- I have a table with dynamically created rows and columns based on user selection of row and column numbers. 2- Each row in the table has the following controls: A- One textbox, one l ...

Programmatically simulating a click on a link within a Windows Universal Windows Platform (U

I am facing an issue with a code that has multiple items with the same href attribute due to it being an external source. I need help figuring out how to programmatically click on a specific link tag using C# within a WebView or by accessing the source d ...

Adjusting the starting position of text within an HTML <li> element

I am currently in the process of designing a webpage layout with three columns. I have a specific vision for how I want the text to align within these columns but I am unsure of how to achieve it. Is there a way to make the text start at an exact position, ...

Is there a way to determine if an input field is currently focused in vue.js?

Is there a way to display a div when an input is in focus using Vue.js? ...

Looking for assistance with aligning UL elements in CSS using absolute positioning for a dropdown effect

I'm currently working on implementing a language switching feature on this website. The concept involves using a SPAN element that reveals a dropdown box (based on UL) containing a list of available languages when hovered over. Below is a preview of t ...