Skip to content

Instantly share code, notes, and snippets.

@gjtiquia
Created March 9, 2024 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gjtiquia/90e1a37d96a84ccae7e146e0693ffd3a to your computer and use it in GitHub Desktop.
Save gjtiquia/90e1a37d96a84ccae7e146e0693ffd3a to your computer and use it in GitHub Desktop.
Open link in new tab in functions workaround for Safari
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Open Link in New Tab</title>
</head>
<body>
<p>Open Link in New Tab Workaround for Safari</p>
<button id="openWindowPromptButton">
Open Prompt
</button>
<button id="openWindowDirectlyButton">
Open Directly
</button>
<script>
const openWindowPromptButtonElement = document.getElementById("openWindowPromptButton");
openWindowPromptButtonElement.addEventListener("click", () => {
openWindowPrompt("https://google.com");
})
const openWindowDirectlyButtonElement = document.getElementById("openWindowDirectlyButton");
openWindowDirectlyButtonElement.addEventListener("click", () => {
openWindowDirectly("https://google.com");
})
function openWindowPrompt(url) {
const response = confirm(`Open ${url} in new tab?`);
if (!response) return;
openWindowDirectly(url);
}
function openWindowDirectly(url) {
// Workaround to force main thread to use in iOS Safari
// Cuz generally only allows opening links from <a> or onclick events in the html, not via scripts.
// Reference: https://stackoverflow.com/questions/20696041/window-openurl-blank-not-working-on-imac-safari
setTimeout(() => {
window.open(url, '_blank');
})
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment