I’m using WKWebView to load a HTML-based string. One of requirements is to be able to copy certain elements to clipboard. I tried a few options. All of them have refresh issues. When the user clicks the link, it will copy the text but the screen always flashes once. It was like that WKWebView is trying to reload the whole page again.
Here are my codes:
let htmlContent = """
<!doctype html>
<html>
<head>
<script>
function newcopySectionText(event) {
// Save the current scroll position
var link = event.target;
var section = event.target.parentNode;
var sectionText = section.innerText.trim().replace(link.innerText.trim(), '');
var temp = document.createElement("textarea");
temp.style.position = "fixed";
temp.style.left = "-9999px";
temp.style.top = "-9999px";
temp.value = sectionText;
document.body.appendChild(temp);
temp.select();
document.execCommand("copy");
document.body.removeChild(temp);
link.classList.remove("original-link");
link.classList.add("copied-link");
}
</script>
</head>
<body>
<div> texts to be copied.
<a href='#' onclick='newcopySectionText(event)' class='original-link'> copy texts</a>
</div>
</body>
"""
let webConfiguration = WKWebViewConfiguration()
webConfiguration.applicationNameForUserAgent = "Chrome"
webConfiguration.websiteDataStore = WKWebsiteDataStore.default()
let contentTextView = WKWebView(frame: .zero, configuration: webConfiguration) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1";
contentTextView.customUserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.3 Mobile/15E148 Safari/604.1";
contentTextView.navigationDelegate = self
contentTextView.loadHTMLString(htmlContent, baseURL: nil)
Tried multiple suggestions from stackoverflow and apple guides. Also tried ChatGPT. Couldn’t find the solution. Please help.