google chrome, close tab event listener - javascript

I'm working on a chrome extension and I need to get the event when the tab is closed so I can fire of an post to a server. This is what I have atm.
chrome.tabs.onRemoved.addListener(function (tabId) {
alert(tabId);
});
But I can't get it to work. Anyone got any ideas?
Edit:
When I'm running it, it says
Uncaught TypeError: Cannot read property 'onRemoved' of undefined
Edit2: manifest.json
{
"name": "WebHistory Extension",
"version": "1.0",
"manifest_version": 2,
"description": "storing webhistory",
"content_scripts":[
{
"matches": ["http://*/*"],
"js": ["jquery-1.7.min.js","myscript.js"],
"run_at": "document_end"
}
],
"permissions" : ["tabs"]
}

You can't use chrome.tabs API in content scripts:
However, content scripts have some limitations. They cannot: Use
chrome.* APIs (except for parts of chrome.extension)
source
What you need to do is to establish communication between content script and background page. Background page has access to chrome.tabs API:
These limitations aren't as bad as they sound. Content scripts can
indirectly use the chrome.* APIs, get access to extension data, and
request extension actions by exchanging messages with their parent
extension.
source
Everything is in the first five paragraphs of content script documentation.

Related

Content script not injected in mail.google.com/tasks/canvas recently

I'm writing a chrome extension that uses content script to make Google tasks web UI look a little better. The extension used to work fine, but it didn't work anymore starting from the recent 1~2 days.
After investigation, it seems that content script does not execute in mail.google.com domain. To verify this, I changed manifest to match all web pages:
manifest.json:
{
"manifest_version": 2,
"name": "Tasks",
"short_name": "Tasks",
"description": "Use Google Tasks in a much nicer way.",
"version": "0.0.2",
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["js/script.js"]
}
]
}
js/scipt.js
alert('Content script is alerting.');
With this change, I can see chrome pop up an alert window when I visit pages like https://www.google.com/, https://stackoverflow.com and etc, but NOT https://mail.google.com/tasks/canvas, OR https://mail.google.com/mail.
Is there anything on mail.google.com that prevents content script from executing? How can I fix this? Thanks!

Chrome extension with declarativeContent.RequestContentScript

I am trying to make a Chrome extension, which will monitor GMail and do something when user starts to write a message. After some study of examples and documentation I have figured out that I should do it with declarativeContent, which reacts on page change.
This is what I have done by now.
manifest.json:
{
"manifest_version": 2,
"name": "Gmail helper",
"version": "0.1",
"permissions": [ "declarativeContent" ],
"background": {
"scripts": ["background.js"],
"persistent": false
}
}
background.js:
chrome.runtime.onInstalled.addListener (function (details) {
chrome.declarativeContent.onPageChanged.removeRules (undefined, function () {
chrome.declarativeContent.onPageChanged.addRules ([{
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { hostEquals: 'mail.google.com', schemes: ['https'] },
css: ["div"]
// css: ["div[aria-label='Message Body']"]
})
],
actions: [ new chrome.declarativeContent.RequestContentScript({js: ["content.js"]}) ]
}]);
});
});
content.js:
alert ("Test");
My plan was to declare a content script that would trigger on page changes in GMail. I have added a declarative rule, which has pageURL, css and actions defined. According to my understanding content.js should be executed when pageUrl and css content match. However, content.js is not executed.
What am I doing wrong?
Thanks.
Running a content script on a site requires permissions for the site, which isn't stated explicitly in the documentation of declarativeContent API, but is deduced by the lack of "This action can be used without host permissions" note, which is present in other actions. The purpose of declarativeContent API is to install extensions from the WebStore without any permission confirmation warning so naturally this API can't grant you access to mail.google.com unless you add it explicitly in your manifest:
"permissions": ["declarativeContent", "https://mail.google.com/"]
From description of your task it looks like you don't need declarativeContent.
You need to add a content script to page if GMail page is open and in content script you need to add a listener to message editor DOM element (or whatever another element you need to track).
Assuming that you know how to do the second, to add content script to GMail page you need to add the following into manifest:
"content_scripts": [
{
"matches": [
"https://mail.google.com/*"
],
"js": ["content.js"]
}
You also don't need background script and permissions in this case.
Note:
Although you don't need to specify permissions, your extension will require to ask them from the user.
During installation, Chrome will warn the user that your extension will have access to all user data on the page to make the user able to cancel installation if he or she does not agree.
In the document description, RequestContentScript is experimental, but it is not. In my test, Chrome version >= 60 is available, but allFrames does not seem to work.
Before using "RequestContentScript", you need to declare host permissions in "permissions".
https://developer.chrome.com/extensions/declarativeContent#type-RequestContentScript

How to get content_scripts to execute in file:/// URLs in a Chrome extension

I can't seem to make this work no matter what I do. Let me demonstrate with a very simple example extension. Here is the manifest.json:
{
"manifest_version": 2,
"name": "Sample Of Content Script",
"description": "Changes the background of a page pink",
"version": "1.0",
"content_scripts": [
{
"matches": [ "<all_urls>" ],
"js": [ "changer.js" ]
}
],
"permissions": [
"webNavigation"
],
"background": {
"scripts": [ "background.js" ]
}
}
Notice that my content_scripts entry matches all_urls, which (according to Google documentation) should match file:/// URLs.
The background.js:
(function (chrome) {
'use strict';
chrome.webNavigation.onCompleted.addListener(function (details) {
chrome.tabs.sendMessage(details.tabId, {
action: 'changeBackground',
color: 'pink'
});
});
})(chrome);
And the changer.js (content script):
(function (chrome) {
'use strict';
chrome.runtime.onMessage.addListener(function (request) {
if (request.action !== 'changeBackground') { return; }
document.body.style.background = request.color;
});
})(chrome);
This extension has been published on the Chrome Web Store so you can see the result in action:
https://chrome.google.com/webstore/detail/sample-of-content-script/bkekbfjgkkineeokljnobgcoadlhdckd
It's a pretty simple extension. Navigate to a page, and it turn's the page's background pink. Unfortunately, it doesn't work for any file:/// URLs. The changer.js script is not loaded into the page, and nothing happens.
Extra info
It actually seems to work just fine when running as an Unpacked extension in Developer mode. Pages loaded from the file system turn pink.
I tried using chrome.tabs.executeScript() instead of putting the script into the manifest. This failed in a more obvious way, saying that I didn't request permissions to modify file:/// URLs in the manifest.
I added "file:///*/*" to the permissions section of manifest.json. That seemed to workwell with chrome.tabs.executeScript(), but the Chrome Web Store rejected the extension, saying that file:/// permissions are not allowed.
I reverted to a content_script section in manifest.json and tried adding "file:///*/* to the matches section in the manifest. Again, this worked in a development build, but when I uploaded it to the Chrome Web Store and then installed it, it didn't work.
<all_urls> indeed covers file:// scheme, but it must be manually activated in the extensions list.
If an extension has permissions that cover file:// scheme, it will have a checkbox "Allow access to file URLs" next to "Allow in incognito". The user must enable that manually; you can help by creating a tab with preconfigured URL, after explaining the process:
chrome.tabs.create({url: "chrome://extensions/?id=" + chrome.runtime.id});

Chrome extension - loading file from localhost to content_scripts

I'm developing Chrome Extension and I need to load a javascript file to content scripts, but that file is being served via webpack-dev-server. So it's approachable only on localhost.
I tried to change my manifest.json:
"content_scripts": [
{
"matches": [
"http://*/*",
"https://*/*"
],
"js": [
"http://localhost:3000/scripts/content_bundle.js"
],
"run_at": "document_end",
"all_frames": false
}
But then I got an error in Chrome Extensions window:
Only local files can be specified in "content_scripts" section.
Solution:
add "permissions": ["http://localhost:3000/scripts/*", "tabs"] to manifest.json
download the script using XMLHttpRequest (there are many examples) in your background script (or better an event page script) when needed
save it in chrome.storage.local or localStorage (so you can load it on every extension start from the storage without redownloading)
inject the script:
add a tabs.onUpdated listener and inject the script using tabs.executeScript
alternatively use declarativeContent API with RequestContentScript action (despite the warning on the doc page it should be actually supported in the Stable channel but of course do some tests first).

Using content scripts/messaging with Chrome Apps (not extension) to send data

So I've been trying to send data from a web page to the Chrome Application (not Chrome Extension). Reading stuff around, according to me, this primarily would require the use of url_handlers for invoking Chrome App from a web page, content scripts to inject JS into the web page and/or Messaging for communication between Chrome Application and the web page.
Also, installed App from it's .crx, else loading unpacked directory leads to this error:
"content_scripts is only allowed for extensions and legacy packaged apps, but this is a packaged app."
Now, I tried injecting JS in the required site. However, on inspecting using Chrome Dev Tools, there's no such entry in the Sources->Content scripts section for that site. It simply didn't inject itself when using a Chrome App. It works perfectly with extensions but I want to use Chrome App for other functionalities.
As an alternative, I looked for Messaging examples where its usage is mentioned as:
"... your app or extension can receive and respond to messages from regular web pages."
But, somehow I couldn't get it working.
Any headers on either of the approaches? Other Suggestions?
manifest.json:
{
"name": "App",
"version": "1.0",
"manifest_version": 2,
"minimum_chrome_version": "31",
"app": {
"background": {
"scripts": ["background.js"]
}
},
"permissions": [
{"fileSystem": ["write", "retainEntries", "directory"]},
"storage",
"http://example.com/*"
],
"externally_connectable": {
"matches": ["http://example.com/*"]
},
"content_scripts": [{
"matches": ["http://example.com/*"],
"js": ["content.js"]
}]
}
Indeed, you can't have content scripts in an app.
However, using externally_connectable is valid.
You have already declared that you want to be externally connectable from example.com. (Note: be careful when defining match patterns, for instance this one does not cover www.example.com)
In example.com's own scripts, you can then include the following:
chrome.runtime.sendMessage("idOfYourAppHere", message, function(response) {
/* ... */
});
And in the app (probably its background script) you can catch that with
chrome.runtime.onMessageExternal.addListener(function(message, sender, sendResponse) {
/* ... */
sendResponse(response);
});
This does require you to know the ID in advance. You can pin it by packing your extension and extracting the "key" field from the manifest. See this question for some more details.

Categories

Resources