tabs.executeScript - passing parameters and using libraries? - javascript

I am writing a Chrome extension that needs to modify pages in a specific domain according to some given parameter, which needs XSS in order to be obtained, so simply using a content script seems impossible. So, I've decided to inject the script using tabs.executeScript.
Now I need to know two things: First, how can I pass parameters to the script when using executeScript? I guess I can use messages, but isn't there a more direct way to pass the parameter while injecting the script?
Second, my script uses jQuery, so I need to include jQuery somehow. It's silly, but I'm not sure how to do it. So far, I embedded jQuery in the HTML page I was writing (for example background.html).

If you don't want to use messaging then:
chrome.tabs.executeScript(tabId, {file: "jquery.js"}, function(){
chrome.tabs.executeScript(tabId, {code: "var scriptOptions = {param1:'value1',param2:'value2'};"}, function(){
chrome.tabs.executeScript(tabId, {file: "script.js"}, function(){
//all injected
});
});
});
(jquery.js should be placed into extension folder). Script options will be available inside scriptOptions variable in the script.js.
With messaging it is just as easy:
chrome.tabs.executeScript(tabId, {file: "jquery.js"}, function(){
chrome.tabs.executeScript(tabId, {file: "script.js"}, function(){
chrome.tabs.sendMessage(tabId, {scriptOptions: {param1:'value1',param2:'value2'}}, function(){
//all injected
});
});
});
You would need to add a request listener to script.js:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
var scriptOptions = message.scriptOptions;
console.log('param1', scriptOptions.param1);
console.log('param2', scriptOptions.param2);
doSomething(scriptOptions.param1, scriptOptions.param2);
});

Building off the direct method above, I was able to inject code into a new tab directly from the background script on my Chrome Extension. However, be advised that the code section of the executeScript command will not simply take variables, but only a string. Therefore, after experimenting, I found we need to setup the string of commands beforehand and include the variables we want. Like this:
var sendCode = 'document.getElementsByClassName("form-control n-gram")[0].value = "' + TMObj.brand + '";';
var TMUrl = "http://website.com";
chrome.tabs.create({ url: TMUrl }, function(tab){
chrome.tabs.executeScript(null, {code: sendCode});
});
});
This worked well!

Better way to include dependencies
Add the dependant libraries (and other .js files) to the background scripts in your manifest.json by:
"background": {
"scripts": [
"jquery.js",
"main.js"
]
List the dependencies before app code so that they are loaded before.
Reference: Register Background Scripts
Note: this would perform eager-loading of the scripts, instead of lazy-loading as with executeScript.

Related

How to communicate with a webpage via browser plugin

How can I communicate from a JavaScript code of a webpage to the main code of the add-on?
For example, something like this: If some element is clicked, in the corresponding event handler of the page script, which is the syntax that can be used to send some message to the main code?
Specifically, something like this, where the frame now must be replaced by a generic webpage. Is it possible?
Edit: I have tried the suggested code, but how I had said, the application returns this error:
console.error: sherlock:
Message: ReferenceError: document is not defined
Stack:
A coding exception was thrown in a Promise resolution callback.
See https://developer.mozilla.org/Mozilla/JavaScript_code_modules/Promise.jsm/Promise
Full message: ReferenceError: document is not defined
Previously my question, I had infact tried something similar without any effect.
Yes it is possible.
document.onload = function() {
var elementYouWant = document.getElementById("someID");
elementYouWant.onclick = console.log("Yup.. It was clicked..");
};
Reference.
The answer to the question is not as trivial as it may seem at first sight. I had also thought of a logic of the type described in the Pogrindis' response.
But here, in the case of interaction between the main script (i.e. that of the add-on) and generic script of arbitrary documents, the pattern is different.
In summary, the interaction takes place in this way:
It is required the API page-mod.
Through the property includes of the object PageMod you create a reference to the document, specifying the URI (wildcards are allowed).
Via the contentScriptFile property it is set the URL of the .js file that will act as a vehicle between the main code and that of the document.
Here's an example that refers to the specific needs of the context in which I am. We have:
an add-on code (the main code);
a Sidebar type html document (gui1.html) loaded in the file that I
use as a simple UI (I advise against the use of Frames, since it does
not support many typical HTML features - eg the click on a link,
etc.) containing a link to a second document (gui2.html) which will then
be loaded into the browser tab (I needed this trick because the
Sidebar does not support localStorage, while it is necessary for me);
a script in the document.
We must create an exchange of information between the two elements. In my case the exchange is unidirectional, from the page script to the main one.
Here's the code (main.js):
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
include: "resource://path/to/document/gui2.html",
contentScriptFile: data.url("listen.js"),
onAttach: function(worker) {
worker.port.on("gotElement", function(elementContent) {
console.log(elementContent);
});
}
});
and in the html page script:
<script type="text/javascript">
[...]
SOWIN = (navigator.userAgent.toLowerCase().indexOf("win") > -1) ? "win" : "nix";
if (SOWIN == "win") {
window.postMessage("win","*");
} else {
window.postMessage("Linux","*");
}
[...]
</script>
Finally in the JS file (listen.js) to be attached to the page script:
window.addEventListener('message', function(event) {
self.port.emit("gotElement", event.data);
}, false);
This is just a small example, but logic I would say that it is clear. The uploaded content scripts are not accessible directly from main.js (i.e. the add-on), but you can create a bidirectional communication through the exchange of messages. To achieve this we have to put ourselves in listening the event Attach of the page-mod. Then, it is passed a worker object to the listener; that worker may be used by the add-on for the exchange of messages.
Here are the references to have an exhaustive picture:
Interacting with page scripts
Communicating with other scripts
page-mod
port
Communicating using "port"
postMessage
Communicating using postMessage

"Chrome Apps" webview.executeScript access guest global varibles

I can access a Chrome App Webview HTML with:
webview.executeScript(
{code: 'document.documentElement.innerHTML'},
function(results) {
// results[0] would have the webview's innerHTML.
});
But I would like to get the value of global variables in the Guest like so:
webview.executeScript(
{code: 'window.globalVar'},
function(results) {
// results[0] should have the webview's value of "globalVar".
});
How can I do this?
An answer to summarize the steps required.
1) You inject a content script with webview.executeScript() into the embedded page.
2) Since the page's real window is isolated, you need a page-level script to access it. You inject it with a <script> tag as discussed here.
3) The page-level script can access the window object, but cannot talk to the app script. However, it can fire a custom DOM event, that the content script can catch. Discussed here.
4) Finally, from the content script you need to send a message to your app script. The content script calls chrome.runtime.sendMessage, while the app script listens with chrome.runtime.onMessage. chrome.runtime.sendMessage does not seem to be available to webview content scripts injected with webview.executeScript(). A workaround is to use postMessage as described here.
It's a bit of an onion structure, that's why you need 2 steps "in" and 2 steps "out". You can't really do it in the return value that's passed to the executeScript callback, since at least one of the "out" steps will be asynchronous.
You can inject a script that inserts a DOM node with the global variable's value. Then you return that node's innerHTML and you have your value right away without using a callback:
var code = "script = document.createElement('script'); script.text=\"var n=document.createElement('span');n.style.display='none';n.id='my-id';n.innerHTML=window.globalVar;document.body.appendChild(n)\"; document.head.appendChild(script);document.getElementById('my-id').innerHTML"
webview.executeScript(
{code: code},
function(results) {
console.log(results[0]);
});
Just use an ID for the DOM node that is not used and you should be fine. It works for me.

Executing code at page-level from Background.js and returning the value

I've got a web page with its own scripts and variables that I need to execute and retrieve return values from my extension's Background.js.
I understand (I think!) that in order to interact with the web page, it must be done via chrome.tabs.executeScript or a ContentScript, but because the code must execute in the context of the original page (in order to have scope to the scripts and variables), it needs to be injected into the page first.
Following this great post by Rob W, I'm able to invoke the page-level script/variables, but I'm struggling to understand how to return values in this way.
Here's what I've got so far...
Web page code (that I want to interact with):
<html>
<head>
<script>
var favColor = "Blue";
function getURL() {
return window.location.href;
}
</script>
</head>
<body>
<p>Example web page with script content I want interact with...</p>
</body>
</html>
manifest.json:
{
// Extension ID: behakphdmjpjhhbilolgcfgpnpcoamaa
"name": "MyExtension",
"version": "1.0",
"manifest_version": 2,
"description": "My Desc Here",
"background": {
"scripts": ["background.js"]
},
"icons": {
"128": "icon-128px.png"
},
"permissions": [
"background",
"tabs",
"http://*/",
"https://*/",
"file://*/", //### (DEBUG ONLY)
"nativeMessaging"
]
}
background.js
codeToExec = ['var actualCode = "alert(favColor)";',
'var script = document.createElement("script");',
' script.textContent = actualCode;',
'(document.head||document.documentElement).appendChild(script);',
'script.parentNode.removeChild(script);'].join('\n');
chrome.tabs.executeScript( tab.id, {code:codeToExec}, function(result) {
console.log('Result = ' + result);
} );
I realise the code is currently just "alerting" the favColor variable (this was just a test to make sure I could see it working). However, if I ever try returning that variable (either by leaving it as the last statement or by saying "return favColor"), the executeScript callback never has the value.
So, there appear to be (at least) three levels here:
background.js
content scripts
actual web page (containing scripts/variables)
...and I would like to know what is the recommended way to talk from level 1 to level 3 (above) and return values?
Thanks in advance :o)
You are quite right in understanding the 3-layer context separation.
A background page is a separate page and therefore doesn't share JS or DOM with visible pages.
Content scripts are isolated from the webpage's JS context, but share DOM.
You can inject code into the page's context using the shared DOM. It has access to the JS context, but not to Chrome APIs.
To communicate, those layers use different methods:
Background <-> Content talk through Chrome API.
The most primitive is the callback of executeScript, but it's impractical for anything but one-liners.
The common way is to use Messaging.
Uncommon, but it's possible to communicate using chrome.storage and its onChanged event.
Page <-> Extension cannot use the same techniques.
Since injected page-context scripts do not technically differ from page's own scripts, you're looking for methods for a webpage to talk to an extension. There are 2 methods available:
While pages have very, very limited access to chrome.* APIs, they can nevertheless use Messaging to contact the extension. This is achieved through "externally_connectable" method.
I have recently described it in detail this answer. In short, if your extension declared that a domain is allowed to communicate with it, and the domain knows the extension's ID, it can send an external message to the extension.
The upside is directly talking to the extension, but the downside is the requirement to specifically whitelist domains you're using this from, and you need to keep track of your extension ID (but since you're injecting the code, you can supply the code with the ID). If you need to use it on any domain, this is unsuitable.
Another solution is to use DOM Events. Since the DOM is shared between the content script and the page script, an event generated by one will be visible to another.
The documentation demonstrates how to use window.postMessage for this effect; using Custom Events is conceptually more clear.
Again, I answered about this before.
The downside of this method is the requirement for a content script to act as a proxy. Something along these lines must be present in the content script:
window.addEventListener("PassToBackground", function(evt) {
chrome.runtime.sendMessage(evt.detail);
}, false);
while the background script processes this with a chrome.runtime.onMessage listener.
I encourage you to write a separate content script and invoke executeScript with a file attribute instead of code, and not rely on its callback. Messaging is cleaner and allows to return data to background script more than once.
The approach in Xan's answer (using events for communication) is the recommended approach. Implementing the concept (and in a secure way!) is however more difficult.
So I'll point out that it is possible to synchronously return a value from the page to the content script. When a <script> tag with an inline script is inserted in the page, the script is immediately and synchronously executed (before the .appendChild(script) method returns).
You can take advantage of this behavior by using the injected script to assign the result to a DOM object which can be accessed by the content script. For example, by overwriting the text content of the currently active <script> tag. The code in a <script> tag is executed only once, so you can assign any rubbish to the content of the <script> tag, because it won't be parsed as code any more. For example:
// background script
// The next code will run as a content script (via chrome.tabs.executeScript)
var codeToExec = [
// actualCode will run in the page's context
'var actualCode = "document.currentScript.textContent = favColor;";',
'var script = document.createElement("script");',
'script.textContent = actualCode;',
'(document.head||document.documentElement).appendChild(script);',
'script.remove();',
'script.textContent;'
].join('\n');
chrome.tabs.executeScript(tab.id, {
code: codeToExec
}, function(result) {
// NOTE: result is an array of results. It is usually an array with size 1,
// unless an error occurs (e.g. no permission to access page), or
// when you're executing in multiple frames (via allFrames:true).
console.log('Result = ' + result[0]);
});
This example is usable, but not perfect. Before you use this in your code, make sure that you implement proper error handling. Currently, when favColor is not defined, the script throws an error. Consequently the script text is not updated and the returned value is incorrect. After implementing proper error handling, this example will be quite solid.
And the example is barely readable because the script is constructed from a string. If the logic is quite big, but the content script in a separate file and use chrome.tabs.executeScript(tab.id, {file: ...}, ...);.
When actualCode becomes longer than a few lines, I suggest to wrap the code in a function literal and concatenate it with '(' and ')(); to allow you to more easily write code without having to add quotes and backslashes in actualCode (basically "Method 2b" of the answer that you've cited in the question).
chrome.browserAction.onClicked.addListener(function(tab) {
// No tabs or host permissions needed!
console.log('Turning ' + tab.url + ' red!');
chrome.tabs.executeScript({
file: 'index.js'
});
});
Here index.js is normal js file to inject in browser
#index.js
alert("Hello from api");

Inject functions/variables to page from a chrome extension

I'm writing a Chrome Extension that adds functionality to certain pages a user visits.
To do that, I'll need to inject a few variables and functions that the page needs to be able to call.
These variables/functions are generated in a content script.
However, since content scripts run in a secluded environment, the host page can not access it.
According to this article:
http://code.google.com/chrome/extensions/content_scripts.html#host-page-communication
it is possible for content script and host page to communicate through the DOM by adding events.
But that's a horrible way to do things, and I'd really like to see some way to inject methods/variables easily.
Is there such a possibility?
Thanks!
If it still interests anybody, I've found a solution communicating between content script and page itself through messages.
Something like this on the sending script:
window.postMessage({ type: "messageType", params: { param: "value", anotherParam: "value" } }, "*"/*required!*/);
And then on the receiving script do something like this:
window.addEventListener("message", function(event) {
// We only accept messages from ourselves
if (event.source != window)
return;
switch (event.data.type) {
case "blabla":
// do blabla
// you can use event.data.params to access the parameters sent from page.
break;
case "another blabla":
// do another blabla
break;
}
});
Here's how I coded it on my extension, http://pagexray.com/extension/
on your manifest.json
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["script.js"]
}
],
on your script.js
(function(){
var script = document.createElement('script');
script.src = "http://example.com/external.js";
script.addEventListener('load', function() { });
document.head.appendChild(script);
})();

Google Chrome Extension - Background.html function question

Is there anyway by adding to this javascript I can ingore anything after the .com/ .net/ .org/ etc for tab.url.
So if tab.url = examplesite.com/blabla/blabla.html it will replace tab.url with examplesite.com/ and ignore anything after it.
Here's my background.html script.
<script type="text/javascript">
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.getSelected(null,function(tab) {
chrome.tabs.create( { url: "http://www.mysite.com/index.php?q=" +tab.url } );
});
});
</script>
Or do I need to program this into mysite to strip the Url? I was wondering if it is possible with Javascript... (not my forte.)
Thank you for any help you may be able to give me.
Unfortunately there is not parseUri function built into javascript but you could build what you're asking for using regular expressions. An example of this can be found here:
http://blog.stevenlevithan.com/archives/parseuri
Also, I've never tried to access it from a Chrome extension, but I suspect you have access to the window.location variable which is an object that contains broken down parts of the current page's url. Trying console.log(window.location) and look at the content of the object.

Categories

Resources