Copy window.location.href to clipboard from extension

I am trying to copy 'window.location.href' e.g. the URL of the current page to clipboard from my extension by clicking on button Copy. My issue is that when I copy the URL to clipboard, it is the extensions URL that is copied and not the page I am visiting. This much makes sense to me, but I am having issues solving it.


Extensionbar:

  
 
<!DOCTYPE HTML>
<html>
  <head>
  <button onclick="copyFunction();">Copy</button>
  <script type="text/javascript">
  function copyFunction() {
  var inputDump = document.createElement('input'),
  hrefText = window.location.href;
  document.body.appendChild(inputDump);
  inputDump.value = hrefText;
  inputDump.select();
  document.execCommand('copy');
  document.body.removeChild(inputDump);
  }
  </script>
  </head>
</html>

From my understanding the solution should be this, but I fear I am too clueless how to proceed:
https://developer.apple.com/documentation/safariservices/safari_app_extensions/passing_messages_between_safari_app_extensions_and_injected_scripts

This is how I (tried to) proceed, by creating a global.html page and an injected script.


Global page:

  
 
<!DOCTYPE HTML>
<script>
  safari.application.addEventListener("command", copyFunction, false);

  function copyFunctionEvent(event) {
  if (event.command == "CopyToClipboard") {
  safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("CopyToClipboard", "all");

  }
}
</script>

Injected script:

function myextension_openAll(event){
  if (event.name == 'CopyToClipboard'){  
  function copyFunction() {
  var inputDump = document.createElement('input'),
  hrefText = window.location.href;
  document.body.appendChild(inputDump);
  inputDump.value = hrefText;
  inputDump.select();
  document.execCommand('copy');
  document.body.removeChild(inputDump);
  }

}
safari.self.addEventListener("message", myextension_openAll, true);


Actual (with only extensionbar.html): Returns safari-extension://com.myextension-0000000000/abc123/extensionbar.htmlActual (with extensionbar.html, global.html and injected.js): Copy function doesn't work but it seems that inputDump will return the URL if I send it to console or as an alert.

Expected: Should return http://www.google.com (e.g. if current tab)

Replies

Surely someone on this forum could help me in right direction? I am not sure how to communicate between the injected script and the bar.

I needed a similar functionality for an extension I've been working on. My approach has been to send a message from JavaScript to the SafariExtensionHandler:


safari.extension.dispatchMessage(MESSAGES.copyUrlToClipboard, {
  url: window.location.href
})


For the Swift code, I then handle this message using the approach mentioned here and paste the URL using NSPasteboard.