Global Variables in Chrome Extensions - google-chrome

Is there a simple way where I can access a global javascript variable through content-scripts in chrome extensions?
Accessing global object from content script in chrome extension
I followed the steps mentioned in the above link, but it did not work out for me. Any help would be much appreciated.
Thanks,
Shankar

I managed to complete it. Thanks for the help. I used simple message passing to retrieve the value from the extension script to the content script. The place where I had missed was, the listener at the extension script needs to be at the background page (I think so). Once I changed that, it worked.

For those from the future looking for an answer to this question, here's how I do it:
function getVariable(v) {
var c = document.createElement("div");
c.id = 'var-data';
c.style.display = 'none';
document.body.appendChild(c);
var s = document.createElement('script');
s.innerHTML = 'document.getElementById("var-data").innerText=JSON.stringify('+v+');';
document.head.appendChild(s);
var data = JSON.parse(c.innerText);
c.remove();
s.remove();
return data;
}
And basic usage:
getVariable('globalVarIWantToAccess');
All this script goes in the content-script, not the code for the main webpage, which means that no co-operation is needed from the webpage itself. Basically, the getVariable function creates a script element which is injected into the main page. This script tag retrieves the requested global variable and puts the data into a new div. The function then gets this data from the new div, deletes the new div, deletes the new script element and returns the data.

Related

How to determine why an alert dialog was displayed by Chrome?

I am trying to fix a bug in a Chrome extension. When the extension is installed an alert dialog containing the message "undefined" will be displayed seemingly at random. This does not happen when the extension is not installed.
There is not one call to alert, confirm, or prompt in the extension source code. How do I find out why the alert dialog is being displayed?
I have attempted adding the following code to one of the background scripts and to one of the content scripts.
var originalWindowAlert = window.alert;
window.alert = function() {
console.trace();
return originalWindowAlert.apply(window, arguments);
}
I have confirmed that this technique works when used in a webpage, but it is not working for the extension.
I have also built Chromium from source code and I am able to reproduce it but so far I have not been able to figure out how to determine the origin of the alert dialog. I have set a breakpoint in the RenderFrameHostImpl::RunModalAlertDialog function but I see no way to determine what caused the breakpoint to be hit.
I am getting desperate.
I asked this question on the Chromium Extensions Google Group. I got the following very useful response from Scott Fortmann-Roe.
If you do the following in a content script:
var originalWindowAlert = window.alert;
window.alert = function() {
console.trace();
return originalWindowAlert.apply(window, arguments);
}
I don't believe it will actually intercept alerts triggered by the page as you are overriding the content script's window.alert method which is different from the page's method (content script JS is isolated from page JS).
To modify the page's alert method you'll probably need to inject a script tag into the page. E.g. something along these lines in the content script:
let script = document.createElement('script');
script.textContent = `
var originalWindowAlert = window.alert;
window.alert = function() {
console.trace()
return originalWindowAlert.apply(window, arguments);
} `;
document.body.appendChild(script);

Is there a way to remove a script from a doc (using the new doc embedded script)

I developed a script extension that uses a Google doc as template AND as script holder.
It gives me a very nice environment to implement a mail merge application (see below).
At some point I use the DocsList class makeCopy(new Name) to generate all the docs that will be modified and sent. It goes simply like that :
var docId=docById.makeCopy('doc_'+Utilities.formatString("%03d",d)).getId();
Everything works quite nicely but (of course) each copy of the template doc contains a copy of the script which is obviously not necessary ! It is also a bit annoying since each time I open a copy to check if data are right I get the sidebar menu that opens automatically which is a time consuming process ...
My question is (are) :
is there any way to remove the embedded script from the copy ? (that would be simple)
or should I copy all the doc elements from the template to an empty document ? (which is also a possible way to go but I didn't try and I don't know what will be in this doc in real life use...
Shall I get a perfect clone in any case ?)
I've read the doc and didn't find any relevant clue but who knows ? maybe I missed something obvious ;-)
below is a reduced screen capture to show the context of this question :
Following Henrique's suggestion I used a workaround that prevents the UI to load on newly created documents... (thanks Henrique, that was smart ;-)
The function that is called by onOpen now goes like that :
function showFields() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var find = body.findText('#'); // the new docs have no field markers anymore.
if(find != null){ // show the UI only if markers are present in the document.
var html = HtmlService.createHtmlOutputFromFile('index')
.setTitle("Outils de l'option Publipostage").setWidth(370);
ui.showSidebar(html);
}
}

How can I unShow() after Spreadsheet.show(HtmlOutput)?

I have this working very nicely :
var theForm = HtmlService.createTemplateFromFile('aForm').evaluate();
var theSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
theSpreadsheet.show(theForm);
When the user has submitted data I want to close "theForm". Is there something like an unShow() or hide() method on a spreadsheet? a harikiri() method on an HtmlOutput?
Ideally, I'd like to have a reShow() command that saves the submitted data, refreshes the spreadsheet and calls show() again.
I have found no way to do these things, so I just disable the submit button. Ugh!
Any suggestions greatly appreciated.
UPDATE (2012/08/28) : I should have mentioned that I am calling back into the same code as originally opened "theForm", from the HTML form, using this call ...
google.script.run.recordTheForm(jsonTheForm);
Do I assume correctly that google.script.run.*() calls have no knowledge of any variable values set earlier?
HtmlService doesn't have an equivalent of app.close()... this is an oversight, not something by design, and we will fix it.
Edit: From within client-side JavaScript code (not from the server like app.close(), but within the HtmlService code itself) you can now call google.script.host.closeDialog()
Call this:
theForm.close();
SpreadsheetApp.flush();
theSpreadsheet.show(theForm);
Good luck,
Thomas van Latum

Why is e.parameter.source undefined?

I am trying to find out where a callback function came from, but e.parameter.source has been undefined.
The code I'me using to create the callback event is:
var temp_handler = app.createServerHandler("do_things");
container.add(app.createButton(s_list[i][2]).setId("goto_"+s_list[i][1]).addClickHandler(temp_handler));
container.add(app.createLabel("goto_"+s_list[i][1]));
where container is later added to the app.
The first part of the function that gets called is:
function do_things (e)
{
var app = UiApp.getActiveApplication();
Logger.log(e.parameter);
var src = e.parameter.source;
From this, I have been able to tell that e.parameter is:
{clientY=61, clientX=38, button=1, alt=false, eventType=click, screenY=278, ctrl=false, screenX=493, y=11, shift=false, meta=false, x=34}
This does not include source. I find this peculiar because as far as I can tell, other callback functions in the same file have been able to access and use e.parameter.source without issue.
Does anyone know what I am doing wrong in this callback such that the source parameter is inaccessible?
The other answers do not make much sense to me.
First, because the source parameter is filled by the element id that generated the event, not its name.
Also it's filled automatically, there's no need to addCallbackElement, which is required for accessing widgets contents by their name. And last, set a name for a label is only useful when you're setting a tag on it, as there's no "content" for a label.
All that said, the only problem I can imagine is if you're setting the same id on another widget and it's messing with your original one (the button). But I haven't tested that to be sure.
You simply forgot to give a name to your Label widget. The value returned by the e.parameter is assigned to a widget by its name.
The ID is used to access the widget from outside the UiApp creation function when you need to modify it.
In addition to what Serge answered, you might want to supply a callback element on the handler using
ServerHandler.addCallbackElement()

listen to keystrokes from different pages

I want to develop an extension that runs in the background and listens to keystrokes and stores them as a string in a variable. For example, if I have 5 tabs in a chrome browser window and I press a,b,c,d,e on each tab of the window; the final string should be abcde.
Could any please provide a sample code for this?
Help will be greatly appreciated.
You could add code like this to a content script:
var bodyElement = document.getElementsByTagName("body")[0];
bodyElement.addEventListener("keypress", function(e){
console.log(e);
console.log(String.fromCharCode(e.keyCode));
});
The body element must be loaded for this code to work, so use jQuery's $(document).ready(), or similar, or in the extension manifest set the run_at value for the script to document_end.