Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extensions: Detect copy action from Window's URL bar

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?

like image 902
Clifford Fajardo Avatar asked Oct 16 '25 14:10

Clifford Fajardo


1 Answers

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.

like image 54
Denis L Avatar answered Oct 18 '25 09:10

Denis L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!