How to debug Chrome extension example with code injection? - javascript

maybe this question is a bit noob style but I don't understand this JavaScript stuff.
My question: how do I debug injected code of the following
chrome extension example?
The file popup.js executes send_links.js (this is the injected file, if I understand this correct). I would like to debug send_links.js. I cannot set any breakpoint because I cannot see send_links.js in the Developer Tools of Chrome. I tried the command "debugger;" in send_links.js but it does not work. "console.log("blah");" commands are ignored too.
Thank you!

The debugger keyword will work if you open the Developer Tools for the current tab before you press the action button.
Also, if you want the script to display with its name, add the following line anywhere in send_links.js:
//# sourceURL=send_links.js
Then the script will show up in the 'Content Scripts' tab of the Developer Tools of the current tab. There you can set breakpoints and such. But you need always to open the Developer Tools for the tab before pressing the button for this to work.

All Injected Files or Content Scripts are Exposed to Page Developer Tools, You can set breakpoints and all regular stuff you do on regular Java Script Pages.
(source: google.com)
All your console log(s) appear in the page they are injected.
Ex:
If i inject console.log(document.getElementsByTagName('body')[0].style); to http://www.google.co.in/, then i need to open devtools of http://www.google.co.in/ page and look in its console.
The Output appeared is similar to regular debugging result.
EDIT 1
They are exposed through chrome.tabs.executeScript() but indirectly, when you set debugger; command you can inspect code.
Demonstration
If some sample code injects
chrome.tabs.executeScript(35, {
"code": "console.log('hi');debugger;//# sourceURL=send_links.js"
});
debugger of page shows the script being injected.

I guess it's because you open the debugger tool on the tab and not on the extension. Right click on the icon of your extension and choose the Inspect popup menu item. You can find more informations on this page http://developer.chrome.com/extensions/tut_debugging.html

In this case the script is not injected until you open the popup. Once the popup window loads, it injects send_links.js, which in turn sends a message as soon as it is done getting the links. You could reverse this messaging and inject the file in the manifest:
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["send_links.js"]
}],
add an on message handler to send_links.js with support to send a response
chrome.extension.onMessage.addListener(function(message,sender,sendResponse){
[...]
sendResponse(links);
});
and then replace the onMessage handler and executeScript in the popup with a sendMessage callback
chrome.windows.getCurrent(function (currentWindow) {
chrome.tabs.query({active: true, windowId: currentWindow.id},function(tab) {
chrome.tabs.sendMessage(tab[0].id, {method: "getlinks"},function(links){
for (var index in links) {
allLinks.push(links[index]);
}
allLinks.sort();
visibleLinks = allLinks;
showLinks();
});
});
});
This arrangement will put send_links.js into every page so that you can debug it more easily. Once it is bug free you can switch back to programmatic injection because in cases like these it is more efficient.
You can find the script under Sources > Content Scripts > One of them (plfdheimenpnchlahmhicnkejgmhjhom for example).
Edited source files

Related

Chrome Extension: How can I load a content.js file conditionally?

I am not talking about executing a content script conditionally.
I know how to do that via if (...) { chrome.scripting.executeScript(...) }
I'm talking about not even having the content.js file available in the page's source code unless a condition is met.
In order for a Chrome Extension content script to run on a page, I need to declare it in the manifest like so:
"content_scripts": [
{
"matches": ["https://allowed-host/*"],
"js": [ "content.js" ]
}
]
However, with the above, as soon as the user goes to https://allowed-host/* the content.js file becomes available on the Sources panel from what I can see (even if my extension chooses not to use it just yet).
I'm trying out https://extensionpay.com/ which is supposed to allow you to create subscription-based chrome extensions.
Inside background.js you can use the ExtPay API to see if the user has paid or not and execute code accordingly.
But my Chrome Extension relies on content scripts running on the page and manipulating the DOM and those script files themselves are available for anyone to view as soon as the relevant page loads, regardless of subscriptions etc.
Is there a way to prevent that ?
I understand I could set up my own server for this but I'm wondering if there is a no-backend-involved solution, only through the Chrome Extension API, where I could load a file on the page conditionally. Again, I'm not talking about executing the file conditionally, but loading it on the page, and making its source code available for anyone to view conditionally.
Thanks for any help.

Chrome Extension: How to convert a local HTML file into a URL to display?

I am currently developing a chrome extension, and am attempting to make one of my local HTML files into a URL so I can open it from my content script. One solution I found was to use:
chrome.tabs.create({url: chrome.extension.getURL('notes.html')});
This did not work though. Some people have reported that content scripts may not work with all of the chrome extension API. I need this function to work from my content script though, to make sure it will fire when I need it to. I also found:
var urlChanged = window.url.createObjectURL("notes.html");
window.open(urlChanged);
This did not work either. I ended with trying:
var urlChanged = chrome.runtime.getURL("notes.html");
window.open(urlChanged);
A new tab opens, but I only get a blank HTML page. I was wondering if anyone can give me some insight as to why none of these methods may be working?
tl;dr My content script does not want to open and display a local HTML file I made. I used multiple methods to try and open it, but the file does not want to open from the content script. The HTML file is in the same extension folder as the content script and manifest.json. Any help with this would be appreciated!
To open your extension's page via window.open() in a content script you'll have to expose it using web_accessible_resources in manifest.json. It'll make your extension detectable from web though.
"web_accessible_resources": [
"notes.html"
]
A better solution is to send a message from the content script to the background script, which can use chrome.tabs API to open your extension page.
It's a better solution because window.open from a web page tab may be blocked by the anti-popup policy. And also because you don't expose your extension's pages to the web.
manifest.json should declare the background script:
"background": {
"scripts": ["background.js"],
"persistent": false
}
content script simply sends a message:
chrome.runtime.sendMessage({action: 'openNotes'});
background.js does the work:
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
switch (msg.action) {
case 'openNotes':
chrome.tabs.create({
url: '/notes.html',
active: true,
index: sender.tab.index + 1,
openerTabId: sender.tab.id,
});
return;
}
});

Go to source code line in Chrome dev tools extension?

I want to make a dev tools Chrome extension that lets the user go to specific points in the page's source code (whenever the page's source code calls some global function foo that I inject into the page via an extension content script).
I can get a stack trace by having function foo throw an exception and then catch it.
But how can I tell Chrome dev tools to go navigate to a certain line in the source code? Is there an API call for that?
There's an API function just for that, chrome.devtools.panels.openResource.
Note that line numbers are zero-based for this API.
// Opens line 34 of file https://example.com/test.js, assuming this resource is present:
chrome.devtools.panels.openResource("https://example.com/test.js", 33, function() {
// Resource should be open, but no way to test that it succeeded
});

How to debug JavaScript on Firefox without Firebug?

How can I debug JavaScript on Firefox without Firebug? I found that not all JavaScript source files, which were being loaded initially, are shown on the left panel of the debug tool. Any chances for me to dig them out?
More background: We have to do remote debugging on a customer's machine and this machine has everything blocked except our remote connection. Also, the customer is refused to install Firebug.
Firefox has built-in devtools, which can be opened via F12 when Firebug is not installed, Ctrl+Shift+I or via Firefox menu > Developer > Toggle Tools:
Their Debugger panel can be opened via Ctrl+Shift+S. It works similar to the one in Firebug.
Note that to be able to debug dynamically evaluated scripts (e.g. scripts executed via eval()), the scripts need to include a //# sourceURL comment.
Note: If they don't include that comment, they won't be shown within the Sources side panel!
See the following example for such a //# sourceURL comment (taken from the linked MDN website):
var button = document.getElementById("clickme");
button.addEventListener("click", evalFoo, false);
var script = "function foo() {" +
" console.log('called foo');" +
"}" +
"foo();//# sourceURL=my-foo.js";
function evalFoo() {
eval(script);
}
The Firefox DevTools have a feature called 'black boxing' to detect JS libraries and automatically exclude them from debugging, because people normally only want to debug their sources but not third party sources. Those scripts will still be listed within the Sources side panel and blacklisting can be turned off for them manually.

chrome extensions - Content Scripts on demand

I wrote my small extension for Chrome which works in the context of the webpage.
Everything is fine, except that code is executed every time when I visit URL defined in the manifest.json in content-scripts matches.
What I would like is to launch it manually - 'on demand' - after clicking on the icon of the extension next to the url bar.
Is this possible?
Yes - it is possible.
I've took it from: http://developer.chrome.com/extensions/content_scripts.html
The relevant part is:
"...To insert code into a page, your extension must have cross-origin permissions for the page. It also must be able to use the chrome.tabs module. You can get both kinds of permission using the manifest file's permissions field. Once you have permissions set up, you can inject JavaScript into a page by calling executeScript()..."
/* in background.html */
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null,
{code:"document.body.bgColor='red'"});
});

Categories