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

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

Related

Chrome extension executescript into external drive file

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;
});

chrome.tabs.executeScript with new browser tab not working?

I'm trying to make a Chrome extension which runs a script whenever the user opens a new tab.
I have the following basic code which is supposed to just paint the page red whenever the extension button is clicked.
It seems to work fine when I navigate to an actual website (ex: here on stackoverflow.com, click my extension icon, page becomes red). However, if I just create a brand new tab and click the button, the popup loads but the page never changes color.
manifest.json:
{
"manifest_version": 2,
"name": "ConsoleTap",
"version": "0.1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "menu.html"
},
"permissions": [
"tabs",
"<all_urls>",
"https://ajax.googleapis.com/"
]
}
menu.html:
<!doctype html>
<html>
<head>
<script src="menu.js"></script>
</head>
<body>
hello
</body>
</html>
menu.js:
document.addEventListener('DOMContentLoaded', function() {
chrome.tabs.executeScript(null,{code:"document.body.style.backgroundColor='red'"});
});
Any ideas on why the page won't update the background color on a new tab? I'm guessing the DOMContentLoaded is never fired or it's listening after the load occurs somehow?
Chrome doesn't allow content scripts on its internal pages: more info
In Chrome 60 and older it was still possible to inject content scripts into the child frames of the default new tab page because it consists of several frames so the restriction only applies to the top level frame. For the default newtab (not some newtab extension) we can match its frame url (https://www.google.com/_/chrome/newtab*) to inject a content script which will activate once a message from the popup is received:
manifest.json:
{
"name": "executeScript",
"version": "1.0",
"content_scripts": [{
"matches": ["https://www.google.com/_/chrome/newtab*"],
"js": ["newtabcontent.js"],
"run_at": "document_start"
}],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
],
"manifest_version": 2
}
newtabcontent.js:
chrome.runtime.onMessage.addListener(function(msg) {
if (msg == "activate") {
document.body.style.background = 'red';
document.body.style.backgroundColor = 'red';
}
});
popup.js:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
if (tabs[0].url == "chrome://newtab/") {
chrome.tabs.sendMessage(tabs[0].id, "activate");
} else {
chrome.tabs.executeScript({
code: "document.body.style.backgroundColor='red'",
allFrames: true
});
}
});
Notes:
When this extension is installed and its permissions are displayed the user will see that it can "Read and change your data on www.google.com".
chrome.tabs.executeScript can't be used on newtab page because it instantly fails for the main frame due to unsupported scheme chrome:// and doesn't even proceed to execute on child frames.

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.

Fire extension on very page Google Chrome Extension

I'm building a Google Chrome extension and want to autoload my extension on every new page, so that I can get the current url and check in a Database some data for it. I want to do it a bit like the adblockers and show how many ads where blocked with the badgetext. Anyway I don't get it workig to autoload on every new page I open. It loades once and then stays there. It only reloads when I click on the Icon to get the popup.html.
Here my Manifest:
{
"manifest_version": 2,
"name": "Some name",
"description": "Some desc.",
"version": "1.0",
"permissions": [
"tabs",
"background"
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"],
"persistent": false
}
}
My background.js looks like this
chrome.windows.onFocusChanged.addListener(function(){
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
// do some stuff with the new url
});
});
Someone have a hint?
I would use chrome.tabs API instead of chrome.windows API.
http://developer.chrome.com/extensions/tabs.html
onCreated event and onUpdated event should work.
chrome.tabs.onCreated.addListener(function callback)
chrome.tabs.onUpdated.addListener(function callback)