I have made a chrome extension to run on GMail, in which I would like to trigger a Google app Script with a button I made. Can anyone tell me how to trigger/call Google script.
This is my script:
function myFunction() {
var thread = GmailApp.getInboxThreads(0,1)[0];
var message = thread.getMessages()[0];
var sub = message.getSubject();
var body = message.getPlainBody();
var text = /(Event)|(Party)/;
result = sub.match(text);
if(result == null) {
result = body.match(text);
}
var q=0;
var labels = GmailApp.getUserLabels();
for (var i = 0; i < labels.length; i++) {
if(labels[i] === "Events") {
break;
}
else
q++;
}
if(q==labels.length)
GmailApp.createLabel("Event")
if(result != null) {
label = GmailApp.getUserLabelByName("Event");
label.addToThread(thread);
}
GMailApp.createLabel("Event");
}
My manifest.json file is below.
{
"manifest_version": 2,
"name": "drc",
"version": "0.1",
"background": {
"scripts": ["bg.js"]
},
"content_scripts": [
{
"matches": [
"https://mail.google.com/*",
"http://mail.google.com/*"
],
"js": ["content.js", "onclic.js"],
"css": ["drpdwn.css"]
}
],
"browser_action": {
"default_title": "Append Test Text"
},
"web_accessible_resources": ["logo.png", "jquery-1.10.2.min.js"],
"permissions": [
"tabs",
"activeTab",
"https://mail.google.com/*",
"http://mail.google.com/* ",
"https://www.googleapis.com/auth/gmail.*"
]
}
Now whenever a user install my extention, google script function should also be installed automatically, How do I do that.
Use the doPost() or doGet() trigger and execute your Google Apps Script.
Related
I'm trying to modify the referer-policy header with my Chrome extension, but it doesn't affect the response headers.
Manifest.json:
{
"name": "My Example Extension",
"version": "1.0",
"description": "",
"permissions": [
"webRequest",
"webRequestBlocking",
"*://*/*"
],
"background": {
"scripts": ["background.js"],
"persistent": true
},
"manifest_version": 2
}
background.js:
chrome.webRequest.onHeadersReceived.addListener(details => {
let header = details.responseHeaders.find(e => e.name.toLowerCase() === 'referrer-policy');
// Check if the header has been defined already
if (typeof header !== 'undefined') {
console.log ('Modifying header');
header.value = 'strict-origin';
}
else {
details.responseHeaders.push({ name: 'referrer-policy', value: 'strict-origin' });
}
return {responseHeaders: details.responseHeaders};
}, {urls: ["*://*/*"]}, ['blocking', 'responseHeaders']);
I added debug outputs which show that the code modifies or adds the header accordingly but there is no effect in the browser itself.
I was writing exactly the same code when trying to modify response headers in extension.
// manifest.json
"permissions": [
"webRequest", "webRequestBlocking", "https://developer.chrome.com/*"
]
// background.js
chrome.webRequest.onHeadersReceived.addListener(
function(details) {
const newHeader = {name:"foo", value:"bar"};
const responseHeaders = details.responseHeaders.concat(newHeader);
return { responseHeaders };
},
// filters
{
urls: ["https://developer.chrome.com/*"],
},
// extraInfoSpec
["blocking","responseHeaders"]
);
It just doesn't work at all.
Until I've changed the last argument to:
// extraInfoSpec
["blocking","responseHeaders", "extraHeaders"]
It finally works.
By revisiting the document, in the last paragraphs of Life cycle of requests section:
Starting from Chrome 79, ... On the other hand, response header modifications do not work to deceive CORS checks. If you need to deceive the CORS protocol, you also need to specify 'extraHeaders' for the response modifications.
You were not returning the modified headers. Try with:
chrome.webRequest.onHeadersReceived.addListener(details => {
let myResponseHeaders = details.responseHeaders;
let header = myResponseHeaders.find(e => e.name == 'Referrer-Policy');
// Check if the header has been defined already
if (header) {
console.log ('Modifying header');
let headerIndex = myResponseHeaders.indexOf(header);
myResponseHeaders.splice(headerIndex,1);
}
myResponseHeaders.push({ name: 'Referrer-Policy', value: 'strict-origin' });
return {responseHeaders: myResponseHeaders};
}, {urls: ["*://*/*"]}, ['blocking', 'responseHeaders']);
Or with a slightly modified code copied from the documentation:
chrome.webRequest.onHeadersReceived.addListener(
function(details) {
for (var i = 0; i < details.responseHeaders.length; ++i) {
if (details.responseHeaders[i].name === 'Referrer-Policy') {
details.responseHeaders[i].value = 'strict-origin';
break;
}
}
return {responseHeaders: details.responseHeaders};
},
{urls: ["<all_urls>"]},
["blocking", "responseHeaders"]);
I am trying to access all the drafts in Gmail using Gmail Add-ons, but it logs error like this
Access denied: : Missing access token for per message scope authorization. [line: 8, function: buildAddon, file: Code]
My onTrigger function looks like this
function buildAddon(e) {
var cards = [];
var accessToken = e.messageMetadata.accessToken;
GmailApp.setCurrentMessageAccessToken(accessToken);
var draftMessages = GmailApp.getDraftMessages();
for (var i = 0; i < draftMessages.length; i++) {
cards.push(CardService.newCardBuilder()
.setHeader(CardService.newCardHeader()
.setTitle(draftMessages[i].getBody())).build());
}
return cards;
}
And the manifest json file looks like this
{
"oauthScopes": [
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/gmail.addons.execute",
"https://www.googleapis.com/auth/gmail.addons.current.message.action",
"https://www.googleapis.com/auth/gmail.addons.current.message.metadata",
"https://www.googleapis.com/auth/gmail.addons.current.message.readonly",
"https://www.googleapis.com/auth/gmail.addons.current.action.compose"
],
"gmail": {
"contextualTriggers": [
{
"unconditional": {},
"onTriggerFunction": "buildAddon"
}
],
"logoUrl": "https://www.gstatic.com/images/icons/material/system/2x/bookmark_black_24dp.png",
"name": "Draft reminder",
"version": "TRUSTED_TESTER_V2"
}
}
You’re missing the scope for drafts permission.
“https://www.googleapis.com/auth/gmail.compose
Manage drafts and send email”
Here is the reference for scopes:
https://developers.google.com/identity/protocols/googlescopes#gmailv1
I am creating a chrome extension which extracts the inner text of h2> from the page in which the user is browsing. Although I learned about content scripts and have used it but it is not working I don't know where is the problem. If anyone could help me that would be greatly appreciated.
This is the js code:
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('button');
link.addEventListener('click', function() {
updateresult();
});
});
function updateresult() {
var i;
var x =document.getElementsByTagName("h2");
for(i=0; i< x.length ; i++)
{
document.getElementById("result").innerHTML = (x[i].innerHTML + "\n");
}}
This is the manifest file which I am using:
{
"manifest_version": 2,
"name": "Header Extractor",
"description": "Extension to search header",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"16": "icon.png",
"48": "icon.png",
"128": "icon.png",
"default_popup":"popup.html",
"default_title": "Open And Search headers"
},
"permissions": [
"storage",
"activeTab" ,"tabs"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": [ "popup.js"],
"run_at": "document_end"
}
]
}
Have you already created a result div to paste your results in?
Also your current function only returns one h2 value. Let's use concat to output them all together.
function updateresult() {
var i;
var x = document.getElementsByTagName("h2");
var string = "";
for(i=0; i<x.length; i++)
{
string.concat(x[i].innerText + "\n");
}
document.getElementById("result").innerText = string;
}
As a side note, we use innerText instead.
I have an extension to count the number of stylesheets.
When the icon is pressed, the stylesheets of all opened windows or tabs are shown.
However, the extension has no effect on the windows and tabs that are opened later.
How can I solve it ?
manifest.json
{
"name": "StyleSheets counter",
"description": "It counts the stylesheets linked with the web page",
"version": "2.0",
"permissions": [
"tabs",
"*://*/*",
"activeTab",
"debugger"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_icon": "SS Counter"
},
"icons": {
"48": "on.png",
"48": "off.png"
},
"manifest_version": 2
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
executeScriptsInExistingTabs();
});
function executeScriptsInExistingTabs(){
chrome.windows.getAll(null, function(wins) {
for (var j = 0; j < wins.length; ++j) {
chrome.tabs.getAllInWindow(wins[j].id, function(tabs) {
for (var i = 0; i < tabs.length; ++i) {
if (tabs[i].url.indexOf("chrome://") != 0) {
chrome.tabs.executeScript(tabs[i].id, { file: 'counter_ss.js' });
}
}
});
}
});
}
counter_ss.js
var theSheets = document.styleSheets;
alert("Number of stylesheets: " + theSheets.length);
Add onClicked event listener with your function executeScriptsInExistingTabs as callback.
I have already the solution, for the new tabs and for the ones whose URL is changed:
chrome.tabs.onCreated.addListener(function(tab) {
//none is done here
});
chrome.tabs.onUpdated.addListener(function(tabid, info, tab) {
if (info.status == "complete") {
chrome.tabs.executeScript(tabid, {file:'counter_ss.js'});
}
});
The code inside
chrome.tabs.onUpdated.addListener
is run both, when the new tabs are open and when the URL of a tab is changed. So to avoid duplication, none is done in the
chrome.tabs.onCreated.addListener
However, it must be there (altough empty).
I am having problems with my google extension, I have followed what I believe is proper for sending information to a background page, but when I try to run my extension I am hit with "Uncaught TypeError: Object [object DOMWindow] has no method 'closer'" Does anyone know what is happening and why?
popup.html
var i = 0;
function start(){
var bg = chrome.extension.getBackgroundPage();
bg.closer(i); //chrome.extension.sendRequest({});
}
function add(){
i++;
document.getElementById('box').value=i;
}
function sub(){
i--;
document.getElementById('box').value=i;
}
background.html
var ctr = 0;
function closer(int i){
var t=setTimeout("close()",i*500);
}
function close(){
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.remove(tab.id, function() { });
});
}
manifest.json
{
"name": "Hello World!",
"version": "1.0",
"description": "My first Chrome extension.",
"permissions": ["tabs", "background"],
"background_page": "background.html",
"browser_action": {
"default_icon": "icon.png",
"popup": "popup.html"
}
}
you cannot just send message to that bg variable.
There is a special approach to send messages to bg, please read up on sendRequest() etc.
http://code.google.com/chrome/extensions/extension.html#method-sendRequest