automa icon indicating copy to clipboard operation
automa copied to clipboard

How to get active tab url in javascript block?

Open HuangKaibo2017 opened this issue 1 year ago • 3 comments

Is your feature request related to a problem? Please describe. I need a create a concise package and it better with javascript need to get active tab url.

Describe the solution you'd like a source code sample.

Describe alternatives you've considered n/a

Additional context I tried this but failed with error:

Error:

Uncaught SyntaxError: Cannot use import statement outside a module

Source Code:

import browser from 'webextension-polyfill'; async function getActiveTabUrl() { if (typeof browser !== 'undefined' && browser.tabs) { return new Promise((resolve, reject) => { try { browser.tabs.query({ active: true, currentWindow: true }, (tabs) => { const activeTab = tabs[0]; if (activeTab) { console.log('Active Tab URL:', activeTab.url); resolve(activeTab.url); } else { console.warn('No active tab found.'); resolve(null); } }); } catch (error) { console.error('Failed to get active tab URL:', error); reject(error); } }); } else { console.error('Chrome APIs are not available. Make sure this code runs in a Chrome extension environment.'); return Promise.reject('Chrome APIs are not available.'); } }

// Example usage getActiveTabUrl().then(url => { if (url) { console.log(The URL of the active tab is: ${url}); } else { console.log('Could not retrieve the active tab URL.'); } }).catch(error => console.error(error));

automaNextBlock();

HuangKaibo2017 avatar Aug 30 '24 02:08 HuangKaibo2017

I quickly checked how the script is executed (see here). Seems like it's designed to execute custom scripts within the context of the current web page (via document.createElement). This means it operates within the content script's context, directly interacting with the DOM of the page it's injected into. As a result, the script doesn't have direct access to Chrome extension APIs like chrome.tabs.query, which are only available in background scripts, popup scripts, or other parts of the extension that aren't running in the content script.

However, you can use the Get Tab URL Block right before the JS block to get the active URL, assign it to variable / insert it into table, then read & use it in the subsequent JS block.

jingbof avatar Sep 01 '24 05:09 jingbof

thx your help. @jingbof it is good to know background script can access chrome.tabs.query. I learned something from you.

HuangKaibo2017 avatar Sep 09 '24 02:09 HuangKaibo2017

in fact, double check the document, there is a activeTabUrl variable can be ref by automaRefData, like automaRefData('activeTabUrl ', '');

HuangKaibo2017 avatar Sep 28 '24 09:09 HuangKaibo2017