Chrome extension executescript into external drive file - google-chrome

I have created an extension that uses the executescript api to inject a piece of code (shown below) that basically on window.onbeforeunload confirms they want to close the page. I have the script working, and by using the file://*/* permission, got it to inject on file URLs. However, when testing it on a flash game I downloaded, the script didn't inject. The URL was externalfile:drive-randomtext/root/SWFNAME.swf. I tried adding externalfile://*/* in the permissions but got the following error message: There were warnings when trying to install this extension: Permission 'externalfile://*/*' is unknown or URL pattern is malformed. Is there an external file permission, or another way to do this?
Manifest.json:
{
"name": "name",
"short_name": "name",
"version": "3.6",
"manifest_version": 2,
"description": "Desc",
"permissions": [
"storage",
"http://*/",
"https://*/",
"tabs",
"activeTab",
"webNavigation",
"*://*/*",
"file://*/*"
],
"page_action": {
"default_icon": "logo.png"
},
"background": {
"scripts": ["disabled.js"]
}
}
Script that gets executed:
(hotkey-binding code too long, can be found here)
Mousetrap.bind('ctrl+m', function(e) {
window.onbeforeunload = confirmExit;function confirmExit(){alert('confirm exit is being called');return'Close page?';}
alert('Enabled');
return false;
});
Mousetrap.bind('ctrl+q', function(e) {
location.reload();
return false;
});

Related

chrome extension: Getting the source HTML of the current page on page load

I found this answer on how to grab the page source of current tab:
Getting the source HTML of the current page from chrome extension
However, this answer requires user to press the extension popup.
I would like to know how I can access the page source upon loading of page (without having to invoke the popup).
In my background.js I've tired this:
chrome.tabs.onUpdated.addListener(function (tabId , info) {
console.log(info)
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
if (chrome.runtime.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
}
});
});
but this results in the following error:
There was an error injecting script : Cannot access contents of the
page. Extension manifest must request permission to access the
respective host.
My manifest.js:
{
"name": "Getting Started Example",
"version": "1.0",
"description": "Build an Extension!",
"permissions": ["declarativeContent",
"https://www.example.com/*",
"storage",
"activeTab"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],
"options_page": "options.html",
"manifest_version": 2,
"page_action": {
"default_popup": "popup.html",
"default_icon": {
"16": "images/get_started16.png",
"32": "images/get_started32.png",
"48": "images/get_started48.png",
"128": "images/get_started128.png"
}
},
"icons": {
"16": "images/get_started16.png",
"32": "images/get_started32.png",
"48": "images/get_started48.png",
"128": "images/get_started128.png"
}
}
I don't think the issue is really with permissions because I am able to get the page source from the popup.html (which is page_action script). But I am not able to get it via "background" or "content_scripts". Why is that and what is the proper way to accomplish this?
It is about the permissions.
Your example a bit insufficient, but as I can see you are using "activeTab" permission.
According to the activeTab docs, the extension will get access (e.g. sources) to current tab after any of these actions will be performed:
Executing a browser action
Executing a page action
Executing a context menu item
Executing a keyboard shortcut from the commands API
Accepting a suggestion from the omnibox API
That's why you can get sources after opening the popup.
In order to get access to tabs without those actions, you need to ask for the following permissions:
tabs
<all_urls>
Be noted, it allows you to run content-script on every tab, not only the active one.
Here is the simplest example:
manifest.json
{
"name": "Getting Started Example",
"version": "1.0",
"description": "Build an Extension!",
"permissions": ["tabs", "<all_urls>"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"manifest_version": 2
}
background.js
chrome.tabs.onUpdated.addListener(function (tabId, info) {
if(info.status === 'complete') {
chrome.tabs.executeScript({
code: "document.documentElement.innerHTML" // or 'file: "getPagesSource.js"'
}, function(result) {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
} else {
console.log(result)
}
});
}
});

Chrome - Message passing - From popup click to context script on specific tab

Can you tell me why the following code is not working. Here is my code :
Popup.js (not a backgorund script) :
chrome.tabs.create({url: url}, function(tab) {
chrome.tabs.executeScript(tab.id, {file: 'connect.js', allFrames:true}, function() {
chrome.tabs.sendMessage(tab.id, 'whatever value; String, object, whatever');
});
});
content script :
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
console.log(message);
// Handle message.
// In this example, message === 'whatever value; String, object, whatever'
});
And my manifest :
{
"name": "AN App",
"version": "1.0",
"description": "To connect",
"permissions": [
"storage",
"activeTab",
"tabs",
"https://*/*"],
"browser_action": {
"default_popup": "popup.html"
},
"content_scripts": [{
"matches": ["https://*/*"],
"js": ["connect.js"]
}],
/*
"background": {
"scripts": ["background.js"]
},*/
"manifest_version": 2
}
I don't understand, the console debug in the tab do not display anything...
I also try from the popup to the background and then from the background to the tab but nothing happen neither (I'm quite new at chrome extension so I hope u can help me)
Thanks,
Regards
Martin
I found the solution. When I call chrome.tabs.create from the JS inside the popup it closes the code running in the popup and the message is never sent.
So instead of calling the chrome.tabs.create inside the JS linked to the popup, I just send a message to the background script, the background script call chrome.tabs.create (like this it runs in background and the code do not stop from executing).
And then the message function works correctly like chrome doc says.
Martin

Chrome Extension - Append HTML & Run jQuery Function on Extension Click

So I'm in the midst of creating my first Chrome Extension (Trying)
I feel like I'm close... But I genuinely don't know what to google to get the answers I need. So I'm sorry if this is a silly question.
Essentially what I'm trying to do is on click of extension - Append HTML & CSS to body and run a jQuery function. But from the looks of it, I need to call in jQuery in the manifest? Which I think I've done and it's still not working.
My Code:
manifest.json
{
"name": "Title",
"description": "Description",
"version": "1.0",
"browser_action": {
"default_title": "Hover Title",
"default_icon": "icon.png"
},
"content_scripts": [ {
"js": [ "jquery-1.7.2.min.js", "background.js" ],
"matches": [ "http://*/*", "https://*/*"]
}],
"manifest_version": 2
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
(function ($) {
$('body').append("Hello");
alert("Hello");
console.log("Hello");
}(jQuery));
});
Any insight into where I'm going wrong would be massively helpful!
Thank you!!
Chrome extension architecture is simple but it doesn't mean one can write code without studying it.
There are two methods of injecting content scripts:
Unconditionally on all specified urls, in which case "content_script" key is used in the manifest and the content scripts communicate with the background page via runtime.sendMessage.
Only when some event occurs like e.g. the user clicks our toolbar icon, in which case we only need the permission to access the active tab.
So in the given case we'll attach the icon click handler and inject the code afterwards:
manifest.json:
{
"name": "Title",
"description": "Description",
"version": "1.0",
"browser_action": {
"default_title": "Icon Title",
"default_icon": "icon.png"
},
"background": {
"scripts": ["background.js"]
},
"permissions": ["activeTab"],
"manifest_version": 2
}
background.js (this is an event page because we didn't use "persistent": true in the manifest, so be advised that the [global] variables will be lost after a few seconds of inactivity; instead you should use chrome.storage API or HTML5 localStorage/sessionStorage/and so on):
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({file: "jquery-1.7.2.min.js"}, function(result) {
chrome.tabs.executeScript({file: "content.js"}, function(result) {
});
});
});
content.js (the code runs in a sandbox so there's no need to hide global variables using IIFE)
$('body').append("Hello");
alert("Hello");
console.log("Hello");

Can't get Chrome Context Menu item to show on Chrome Extension

I have a Chrome extension that opens a KML/KMZ file in Google Maps. The extension is triggered when the user right-clicks a link to the KML document. But the context menu does not appear. It uses a background script. Here is the manifest.json:
{
"manifest_version": 2,
"name": "KML/KMZ Viewer",
"version": "1.0.0",
"description": "Can be used to view KML/KMZ Files.",
"icons": {
"19": "tiny.jpg",
"24": "icon.png",
"128": "image.png"
},
"permissions": [
"tabs",
"contextMenus",
"activeTab",
"background"
],
"background": {
"scripts": ["background.js"]
}
}
Here is the background.js:
// Set up context menu at install time.
chrome.runtime.onInstalled.addListener(function() {
menuCreate();
console.log('Issued function');
});
// add click event
chrome.contextMenus.onClicked.addListener(onClickHandler);
// The onClicked callback function.
function onClickHandler(info, tab) {
var url = info.selectionText;
openWin(url);
};
function openWin(kml) {
chrome.windows.create({"url":"http://www.nearby.org.uk/google/fake-kmlgadget.html? up_kml_url="+kml+"&up_view_mode=earth&up_lat=&up_lng=&up_zoom=&up_earth_2d_fallback=1&up_earth_fly_from_space=1&up_earth_show_nav_controls=1&up_earth_show_buildings=1&up_earth_show_terrain=1&up_earth_show_roads=1&up_earth_show_borders=1&up_earth_sphere=earth&up_maps_streetview=1&up_maps_default_type=hybrid"});
}
function menuCreate() {
chrome.contextMenus.create({"title": "Open KML/KMZ", "contexts": ["link"], "id": "kmlopen", "targetUrlPatterns": ["*.kml", "*.kmz"]});
console.log('Function ran');
}
Yet when I right-click on a link to a KML or KMZ file, the context menu doesn't show. According to the JavaScript console, the functions ran. This is what the console outputs when I run chrome.contextMenus.create({"title": "Open KML/KMZ", "contexts": ["link"], "id": "kmlopen", "targetUrlPatterns": ["*.kml", "*.kmz"]}); manually under _generated_background_page.html I get the kmlopen, the id of the menu item. What am I doing wrong? The openWin(/*some url*/); function works fine.
Wrong pattern.
The patterns follow the standard Match pattern format.
So you should use the patterns
"targetUrlPatterns": ["*://*/*.kml", "*://*/*.kmz"]
However, be mindful of query strings.

Chrome Extension background scripts aren't being loaded

My chrome extension background script is not being loaded. I followed Googles guide for them but still nothing. I'm not sure if there is another way to check but it isn't in Inspect Element and what the script should be doing isn't happening.
http://developer.chrome.com/extensions/background_pages.html
manifest.json file
{
"manifest_version": 2,
"name": "WebDevFriend",
"description": "blah blah blah",
"version": "1.0",
"permissions": [
"bookmarks",
"tabs",
"http://*/*" ],
"background": {
"scripts": ["js/settings.js"],
},
"browser_action": {
"default_icon": "images/icon.png",
"default_popup": "html/popup.html"
}
}
settings.js file
chrome.windows.onCreated.addListener(function(window){
chrome.windows.getAll(function(windows){
var length = windows.length;
if (length == 2) {
chrome.tabs.executeScript(null, {file: "content_script.js"});
}
});
});
document.write('hello');
First you can't view the background page like a regular html page.
The only way is to view its contents with the Chrome Developer Tools.
just click on generated_background_page.html in the extensions section of your browser.
Second use the console.log() statement to log messages.