Can a browser extension's browser_action script save data to a user-specified file? - google-chrome-extension

My extension has a lot of options and users can save other data, and all of it is in browser.storage.local. I'd like to provide an option to export the data to a JSON file. From a regular page script, I'd use Blob() and saveAs, but saveAs is undefined in the browser_action context I'm using for my settings page which is the natural home for the option.
My extension uses nativeMessaging so I can send the data to my host-based process and do the save from there, but if I prompt the user for where to save it from the host process, that will cause a switch that they probably wouldn't anticipate. I haven't implemented this, so perhaps that would be OK.
My direction question is: Can the JavaScript for a browser extension's browser_action page save a file to the user's device based on the user clicking a button?
I am targeting Chrome and Firefox only and Windows platform only. I'll add support for Mac later after I port the host process.

Did you try downloads.download()? https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/API/downloads/download For example:
const data = JSON.stringify({ boolean: true }, null, 2);
browser.downloads.download({
url: URL.createObjectURL(new Blob([data], { type: 'application/json' })),
saveAs: true,
filename: 'file.json'
});

Related

Is there a way to connect to my existing browser session using playwright

I wish to connect to a website and download some pdf files. The website allows us to view the content only after log in. It asks us to log in using OTP and can't be login at more than 3 devices simultaneously.
I wish to download all the pdf listed. So I previously tried the
python playwright open --save-storage websitename.json
to save the login. But it doesn't work for that specific website.
The website.json file was empty whereas it worked for other websites.
Therefore the only solution I could think of know, is to connect to the current browser, open that website and then download those pdfs.
If you have some solution for this or even some other approach please do inform.
I was also thinking about switching over to puppeteer for the same.
But, I don't know the html parsing using node.js, since I feel using css selectors more comfortable, so I can't switch it.
Playwright is basically same as Puppeteer. So it wouldn't be a problem if you switch between the two.
You can use puppeteer-core or playwright to control your existing browser installation, for example Chrome, and then use the existing user data (Profile) folder to load the specified website login info (cookies, webstorage, etc).
const launchOptions = {
headless: false,
executablePath: '/Applications/Google Chrome/Contents/MacOS/Google Chrome', // For MacOS
// executablePath: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe', // For Windows
// executablePath: '/usr/bin/google-chrome' // For Linux
args: [
'--user-data-dir=/Users/username/Library/Application Support/Google/Chrome/', // For MacOS
// '--user-data-dir=%userprofile%\\AppData\\Local\\Chrome\\User Data', // For Windows
// '--profile-directory=Profile 1' // This to select default or specified Profile
]
}
const puppeteer = require('puppeteer-core')
const browser = await puppeteer.launch(launchOptions)
For more details about Playwright's method, you can check this workaround:
https://github.com/microsoft/playwright/issues/1985
To connect to an already running browser (Chrome) session, you can use connect_over_cdp method (added in v1.9 of playwright).
For this, you need to start Chrome in debug mode. Create a desktop shortcut for Chrome and edit Target section of shortcut properties to start it with debug mode. Add --remote-debugging-port=9222 to the target box in shortcut properties so that the target path becomes:
C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222
Now start Chrome and check if it is in debug mode. For this open a new tab and paste this url in the address bar: http://localhost:9222/json/version. If you are in debug mode, you should see now a page with a json response, otherwise if you are in "normal" mode, it will say "Page not found" or something similar.
Now in your python script, write following code to connect to chrome instance:
browser = playwright.chromium.connect_over_cdp("http://localhost:9222")
default_context = browser.contexts[0]
page = default_context.pages[0]
Here is the full script code:
# Import the sync_playwright function from the sync_api module of Playwright.
from playwright.sync_api import sync_playwright
# Start a new session with Playwright using the sync_playwright function.
with sync_playwright() as playwright:
# Connect to an existing instance of Chrome using the connect_over_cdp method.
browser = playwright.chromium.connect_over_cdp("http://localhost:9222")
# Retrieve the first context of the browser.
default_context = browser.contexts[0]
# Retrieve the first page in the context.
page = default_context.pages[0]
# Print the title of the page.
print(page.title)
# Print the URL of the page.
print(page.url)

How to fetch the value of a key from localstorage which is stored in your browser in a Chrome Extension

I am new to developing Chrome Extensions.
I am trying to get the values for one of the keys which is stored in my browser's localstorage (inspect -> Application -> Localstorage). What I want to do is in my Chrome Extension, when you click a button, I just need it to fetch the value from localstorage for the page which is open in my browser's current tab.
This is the JS function which I am using -
chrome.storage.local.get(['granted.selected'], function(result) {
console.log('Value currently is ' + result.granted.selected);
});
granted.selected - is the name of the key whose value I want to fetch.
When this executes, I get "Value currently is undefined" whereas I want it to fetch the values stored in the above key (granted.selected).
What do I need to add to have this fetch the value for that key from my current open tab's localstorage?
In short - Just want to access a webpage's localStorage from a Chrome extension.
Any help will be greatly appreciated. Thanks!!
chrome.storage.local is not localStorage, it's a completely different storage API.
localStorage is a DOM storage.
To access DOM of a web page you need a content script [1].
Here's an example of programmatic injection in the popup script or in the background script:
chrome.tabs.executeScript({
code: 'localStorage["keyName"]'
}, ([result] = []) => {
if (!chrome.runtime.lastError) {
console.log(result);
// use the result here inside the callback
}
});
Notes:
You'll need permissions in manifest.json as explained in [1].
keyName is the name of the key as seen in devtools "Application" panel of the web page
each part of an extension has its own devtools console.

How to inject script to all frames matching URL from browser extension background-script?

In our browser extension background-script we have a code that injects content-script to all tabs matching specific URL. It is used to activate extension after it is installed without need to reload matching page(s):
chrome.tabs.query({
status: 'complete',
url: 'https://*.example.com/*'
}, function (tabs) {
tabs.forEach(function (tab) {
chrome.tabs.executeScript(tab.id, {
file: 'content-script.js',
runAt: 'document_idle'
});
});
});
Is there a way to inject content-script also to all frames matching this URL? Eg. if somebody has our webapp (app.example.com) embedded in his page (www.acme.com). We need to do it without any additional extension permissions (now they are desktopCapture and https://*.example.com/) or without mentioning www.acme.com anywhere in our extension. Otherwise we would use webNavigation API.

How to open a link in the default browser on Firefox OS?

I have a Firefox OS app where I want a link to open outside of the application (the link is to a different site, and opening it in-application would make the application unusable without a force-quite). How do I do that?
Related bug report
If you don't want to change all the links in the application, you can use WebActivities, e.g. like this:
/*
* Open all external links in the browser
*/
$('a[href^=http]').click(function(e){
e.preventDefault();
var activity = new MozActivity({
name: "view",
data: {
type: "url",
url: $(this).attr("href")
}
});
});
Use target="_blank" on the <a> tag:
<a href='http://different.site/' target='_blank'>Different site</a>
Actually, if you send an app with external links without it to the Marketplace, it should be rejected. so watch out :)

Unable to use getBackgroundPage() api from a devtools extension

I am trying to write an extension that adds functionality to the Chrome devtools.
According to the devtools documentation, it says that the pages in devtools support very limited apis. Any API that is not supported can be access by accessing it through the background page, just as what contentscripts does.
Here is the relevant documentation snippet:
The tabId property provides the tab identifier that you can use with the chrome.tabs.* API calls. However, please note that chrome.tabs.* API is not exposed to the Developer Tools extension pages due to security considerations — you will need to pass the tab ID to the background page and invoke the chrome.tabs.* API functions from there.
Here is the source url: http://developer.chrome.com/extensions/devtools.inspectedWindow.html
However, when I try to do that, I get the following error in the console:
uncaught Error: "getBackgroundPage" can only be used in extension processes. See the content scripts documentation for more details.
Here is my code in my devtools.js script:
chrome.extension.getBackgroundPage().getLocation();
What am I doing wrong?
EDIT
I should describe my scenario first, and show how I am implementing it.
What I want to do is to display extra data in a devtools panel related to a webpage. In order to get that data, I will need to send a HTTP request in the same session as the page being debugged, because it requires authentication.
Use Case:
User browses to a particular URL. He is authenticated to the site. He then invokes devtools. The devtools panel opens up and a new panel shows up that has extra data related to the page.
Implementation:
1) DevTools script finds out the url of the page being inspected. If the url matches the site base hostname, then it opens a panel. In the callback of the panel creation, it sends a message to a background page, asking it to download a JSON payload from a debug endpoint on the same site, and then sends it to the devtools extension, wh ich then displays it.
Problems:
1) The background page gets the request, and downloads the URL. However the download is not using the same session as the user, so the download request fails.
2) From devtools window, I got the tabId of the inspected window. I send this tabId to the background page so that it can parse some stuff out of the url. However, chrome.tabs.get(tabId) does not return the tab.
To summarize, I need to
1) Get the background page to download data in the same session as the user's tab that is being debugged.
2) I need to have the background page be able to get access to the user's tab.
The APIs available to extension pages within the Developer Tools window include all devtools modules listed above and chrome.extension API. Other extension APIs are not available to the Developer Tools pages, but you may invoke them by sending a request to the background page of your extension, similarly to how it's done in the content scripts.
I guess the documentation is little ambiguous, By chrome.extension API they mean the Supported API's for content scripts.
So, you can use long lived communication for communication between inspected page and background page
Demonstration:
The following code illustrate scenario where a devtools page need some information from background page, it uses messages for communication.
manifest.json
Ensured permissions are all available in manifest file
{
"name":"Inspected Windows Demo",
"description":"This demonstrates Inspected window API",
"devtools_page":"devtools.html",
"manifest_version":2,
"version":"2",
"permissions":["experimental"],
"background":{
"scripts" : ["background.js"]
}
}
devtools.html
A trivial HTML File
<html>
<head>
<script src="devtools.js"></script>
</head>
<body>
</body>
</html>
devtools.js
Used Long lived Communication API's
var port = chrome.extension.connect({
name: "Sample Communication"
});
port.postMessage("Request Tab Data");
port.onMessage.addListener(function (msg) {
console.log("Tab Data recieved is " + msg);
});
background.js
Responded to communication request and passed trivial information using tab API()'s
chrome.extension.onConnect.addListener(function (port) {
port.onMessage.addListener(function (message) {
chrome.tabs.query({
"status": "complete",
"currentWindow": true,
"active": true
}, function (tabs) {
port.postMessage(tabs[0].id);
});
console.log("Message recived is "+message);
});
});
Sample Output received for trivial devtools.js here
Let me know if you need more information
EDIT 1)
For your question 1)
Can you make you call(s) from browser extension HTML Page\Content Script so same session is shared, i have tried both the ways in a sample and it is working form me, instead of code in background page- make the code in content script or browser action HTML Page.
Let me know if you are still facing problems.
For your question 2)
The following code always fetches current window user is browsing
manifest.json
Ensure you have tabs permission in your manifest.
{
"name":"Inspected Windows Demo",
"description":"This demonstrates Inspected window API",
"manifest_version":2,
"version":"2",
"permissions":["tabs"],
"background":{
"scripts" : ["background.js"]
}
}
background.js
chrome.tabs.query({
"status": "complete", // Window load is completed
"currentWindow": true, // It is in current window
"active": true //Window user is browsing
}, function (tabs) {
for (tab in tabs) { // It returns array so used a loop to iterate over items
console.log(tabs[tab].id); // Catch tab id
}
});
Let me know if you are still unable to get tab id of current window.

Resources