Writing To Current Tab Console From The Extension Popup
Solution 1:
See Architecture Overview. Depending on what you need to do, it's easy or not.
To interact with the current tab, at a minimum you need Content Scripts. Programmatic Injection is the most suitable for this case.
An absolute minimal extension would be:
manifest.json:
{
/*..required fields like "name"..*/
"background" : {
"scripts" : [ "background.js" ]
},
"browser_action": {
"default_icon": "someimage.png"
},
"permissions" : [
"activeTab"
]
}
background.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id, {file: "content.js"});
});
content.js:
console.log("hi");
This achieves the task of printing a static string in the console. You can, if you need, make a popup page and move the logic from the onClicked
listener to it, for instance if you need multiple links.
The possible complications are numerous.
Suppose you want to print a string that depends on something known in the extension.
Then, you have to employ Messaging or Storage to pass this information to the content script.
Suppose you want to print something that depends on JavaScript running in the page (and not just DOM).
Then, you have to inject your code into the page's context. See also Isolated context.
Suppose you want to execute something in the console, instead of just logging.
You can use the method 2 of executing the code in page's context, but at this point you should consider making a Devtools extension. You can add your own panels, interact with the page using
eval()
with full access to Console APIs. In general, this might be a good idea, if somewhat more complicated. Note that at the time of writing Devtools extensions are subject to a nasty bug.
Post a Comment for "Writing To Current Tab Console From The Extension Popup"