4

Is it possible to listen for a copy event that doesn't occur in the document of an HTML page, such as the browser window's URL bar?

Perhaps there is a Chrome Extension API or a crafty solution that I'm overlooking?

Clifford Fajardo
  • 1,357
  • 1
  • 17
  • 28
  • 1
    There's no built-in API. You can write your own native OS utility to do that, though, and communicate via nativeMessaging with the extension. – wOxxOm Jul 23 '17 at 04:22

1 Answers1

2

Here is the possible solution, is not the best one, but better than nothing.

It monitors text clipboard for URLs, and if a pasted URL is the same as in the current tab - we can consider that it was copied from omnibox.

(Edit: manifest v2 solution)

background.js:

// create element for pasting
const textEl = document.createElement('textarea');
document.body.appendChild(textEl);

var prevPasted = '';
setInterval(function () {
    // paste text from clipboard to focused textarea
    textEl.focus();
    textEl.value = '';
    document.execCommand('paste');
    const pastedText = textEl.value;

    // simple cache check
    if (pastedText !== prevPasted) {
        prevPasted = pastedText;

        if (pastedText.match(/https?:/)) { // you can improve you URL scheme

            // get the current tab
            chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
                var tab = tabs[0];

                // check if current tab has the same URL
                if (tab.url === pastedText) {
                    console.log('Omnibox URL:', pastedText);
                }
            });
        }
    }
}, 500);

Do not forget to add permissions clipboardRead and tabs into the manifest.

Denis L
  • 3,209
  • 1
  • 25
  • 37
  • 2
    This doesn't work anymore with manifest v3 – vim Feb 02 '22 at 14:17
  • @vim, yes, unfortunately, it doesn't. There is a [bug report](https://bugs.chromium.org/p/chromium/issues/detail?id=1160302) about that, but no movement at all – Denis L Feb 03 '22 at 14:42