Connect external js lib to chrome event page - javascript

EDIT - problem solved. I just not reloaded extension properly after changing my manifest. Shame on me.
I'm trying to connect some libs like JQuery to my background.js in chrome extension. Well, I found lots of tips how to do it, but I receive an error. My manifest.json:
{
"manifest_version": 2,
"name": "Chrome WM",
"version": "0.1",
"content_scripts": [{
"matches": ["http://*/*","https://*/*"],
"js": [
"s/jquery-1.11.1.min.js", "s/jquery.soap.js"
]
}],
"background": {
"scripts": ["s/jquery-1.11.1.min.js", "s/jquery.soap.js", "background.js"],
"persistent": false
},
"permissions": [
"tabs",
"activeTab",
"http://192.168.10.150:801/*"
]
}
I probably don't need "content_scripts" section, but just in case.
My background.js:
function siteChanged(activeInfo) {
if (jQuery) {
console.log("Jquery on");
} else {
console.log("Jquery off");
}
// Lots of things here
}
chrome.tabs.onActivated.addListener(siteChanged);
Okay, if I remove this "if (JQuery)" thing whole script works fine, but if not I'm receive such error when event occured:
Error in event handler for tabs.onActivated: ReferenceError: jQuery is not defined
at siteChanged (chrome-extension://flhbfgingimkoknegkcnchnhjdmnhcji/background.js:6:6)
There IS jquery-1.11.1.min.js script in s folder relatively background.js file, and if I create html page beside this background script, grab this jquery-1.11.1.min.js and check if it connected properly - all fine.
What I doing wrong?

Related

Auto start chrome extension

I am trying to make a chrome extension that redirects to a other page when it's loaded. For example, if it's google.nl, go to google.nl?example I managed to get that working, but only when i press the extension button. I want to run the script from the background.js but i get the error:
Uncaught TypeError: Cannot read property 'onBeforeRequest' of undefined
Why do i wan't to reload? Well i don't. it's just to test. The original plan is reading the URL and put the open graph data in my extension.
manifest (part)
"content_scripts": [{
"matches": [
"<all_urls>"
],
"js": ["background.js"]
}],
"permissions": [
"tabs",
"activeTab",
"webRequest"
],
"background": {
"scripts": ["background.js"]
}
background.js
chrome.webRequest.onBeforeRequest.addListener(function(a) {
if (a.url.indexOf("http://www.google.com/") >= 0) {
reloadExtensions();
chrome.tabs.get(a.tabId, function(b) {
if ((b.selected == false)) {
chrome.tabs.remove(a.tabId)
}
});
return {redirectUrl: chrome.extension.getURL("close.html")}
}
return {cancel: false}
}, {urls: ["http://reload.extensions/"],types: ["main_frame"]}, ["blocking"]);
iirc the docs say you need to put all the URL's you want to redirect in the permissions array.
If you don't you will see the following error
Checkout Catblock example https://developer.chrome.com/extensions/samples#search:webrequest by removing
I don't think you need the content script parts at all, in fact I suspect that is where you are seeing the error.

Chrome extension inject js

I want to create a new chrome extension but it don't work.
I want to inject a js file into web page (all web page,not only one.If i push the chrome icon on google the script must execute,if i push the icon on facebook it must execute ect.)
this is background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({
null,{file: "backgrounds.js"} });
});
this is backgrounds.js
document.body.innerHTML="display div elem with style and id";
this is manifest.json
{
"name": "MyExt",
"description": "an extension,what else?",
"version": "1.0",
"permissions": [
"activeTab"
],
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["background.js"]
}
],
"browser_action": {
"default_title": "myExt"
},
"manifest_version": 2
}
what i wrong?
I'm on windows 8.1 Update 1 with chrome last version
Your manifest is wrong: you should set background.js as your background script:
"background" : { "scripts" : [ "background.js" ] },
and remove the "content_scripts" section.
The "activeTab" permission means that you don't need to specify host permissions to inject in the current tab upon browser action click, so no other permissions are needed.
The tabId argument is optional, you can just drop it instead of passing null. And your invocation is wrong (you're wrapping two arguments in a single object). Here's the correct way:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({file: "backgrounds.js"});
});

Chrome extension that acts only when clicked on certain webpages

I'm trying to get my Chrome extension to pop up an alert when the user is on http://google.com/ and clicks on the extension icon.
I have the following manifest:
{
"manifest_version": 2,
"name": "One Megahurt",
"version": "0.1",
"permissions": [
"activeTab"
],
"background": {
"scripts": ["bg.js"],
"persistent": false
},
"browser_action": {
"default_icon": "icon.png"
}
}
and this is bg.js:
chrome.browserAction.onClicked.addListener(function(tab) {
alert('Test!');
})
This code will allow popup an alert on any website, as I don't have any restrictions on which websites this works on. I tried using
if(tab.url === "https://google.com/")
between the first and second lines, but that didn't work.
I'm not sure if I should even be using a background script rather than a content script. I looked in Google's examples and tried using the implementation in "Page action by URL", but that didn't work for me either.
Any help would be appreciated. I should note that I don't really care about the specific issues with the URL--google.com is merely an example. I want to learn to use this for other projects and websites.
EDIT: Adding urls to permissions doesn't restrict which websites the alert pops up on, either.
I ended up using page actions for my solution, per Felix King's suggestion. In retrospect, this was the best solution to use because it doesn't load the extension on every page and cause browser slowdowns (as far as I know).
In addition to adding domains to permissions in the manifest, add a the following code to a background.js.
// When the extension is installed or upgraded ...
chrome.runtime.onInstalled.addListener(function() {
// Replace all rules ...
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
// With a new rule ...
chrome.declarativeContent.onPageChanged.addRules([
{
// That fires when a page's URL matches one of the following ...
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlMatches: 'http://google.com/' }, // use https if necessary or add another line to match for both
}),
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlMatches: 'http://facebook.com/*' },
}) // continue with more urls if needed
],
// And shows the extension's page action.
actions: [ new chrome.declarativeContent.ShowPageAction()]
}
]);
});
});
chrome.pageAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, { file: "script.js" });
});
Key sections to add in manifest.js are:
"background": {
"scripts": ["res/background.js"],
"persistent": false
}
&
"permissions": [
"declarativeContent", "tabs", "activeTab", "http://google.com", "http://facebook.com/*"
]
I don't have much experience with this, but looking at the example manifests that I've seen, they usually have the a list of domains under permissions. I'm betting that if you used:
"permissions": ["http://www.google.com/", "https://www.google.com/", https://google.com, https://google.com],
it would only run the code on the permissible pages.
Pulled example from:
http://developer.chrome.com/extensions/overview
More detailed info here:
http://developer.chrome.com/extensions/declare_permissions

Can't xhr file inside of Chrome extension

I'm building out an extension and I'm trying to keep it well structured. Part of it will use a templating system of some type (Mustache, Handlebars, etc). Note that I'm already aware of having to use a specific non-eval version of what ever library I go with.
The problem is that from within the app.js script (the core logic) I cannot XHR to load the contents of the files in /templates (see below).
The load event never fires, and when I examine with onreadystatechange it immediate jumps to state 4 with a status code of 0. (state 4 and status 200 are what we want).
Getting the Chrome url for the file works, e.g.
chrome.extension.getURL('templates/view1.html')
//chrome-extension://hdhpjlpbepobcdgnkklnakdpoojaahjg/templates/view1.html
I suspect there's something in my manifest.json that isn't configured right. I've read through the CSP docs but nothing is jumping out at me why accessing files local to the extension should be denied. Note that the XHR requests don't throw errors, they just never return data.
The structure of the app is like this:
/manifest.json
/src
app.js
style.css
/libs
jquery.js
mustache.js
/templates
view1.html
view2.html
Manifest.json
{
"name": "Test Extension",
"version": "0.0.1",
"manifest_version": 2,
"icons": {
// "16": "",
// "48": ""
// "128": ""
},
// "default_locale": "en",
"permissions": [
"contentSettings",
"http://*/*",
"https://*/*"
],
"content_scripts": [
{
"matches": [
"https://www.google.com/search*"
],
"css": [
"src/style.css"
],
"js": [
"src/app.js",
"libs/jquery.js",
"libs/mustache.js"
],
"run_at": "document_start"
}
]
}
You need to list the files you want to load in a web_accessible_resources section in your manifest.

Communication between scripts in Chrome Extension

I know there are many variations of this question already in existence here, but none of them seem to work for me.
Details:
I'm writing an extension that pulls some email data from emails you send in gmail. In order to achieve this I am using this version of Gmailr https://github.com/joscha/gmailr.
In effect, I have three content scripts: Gmailr.js and main.js (which are pretty much identical to those in the link above) allow me to pull out the information I'm looking for. Then content.js I use to send a message to the background page of the extension.
The problem is that from gmailr.js and main.js I cannot use any of the Chrome APIs, and I'm not really sure why, so I can't send messages from these back to the background page.
That is why I made content.js which can communicate with the background page. However, it does not seem to be able to see anything the other content scripts do. For example, main.js inserts a div at the top of the page. When I try to attach an event listener to a button in this div from content.js, I am told that no such element exists.
How can I get the data pulled out by main.js to be seen by content.js? (I also tried to put the data in local storage, then trigger a custom event listener to tell content.js to read local storage, but no luck because they don't seem to be able to hear each other's event being triggered).
Any insight or alternatives are much appreciated.
(I can post code if necessary, but it's fragmented and long)
My manifest file:
{
"manifest_version": 2,
"name": "Email extractor",
"description": "Extracts data from emails",
"version": "1.0",
"background": {
"script": "background.js"
},
"content_scripts": [
{
"matches": [
"*://mail.google.com/*",
"*://*/*"
],
"js": [
"lib/yepnope.js/yepnope.1.5.4-min.js",
"lib/bootstrap.js",
"main.js",
"gmailr.js",
"content.js"
],
"css": [
"main.css"
],
"run_at": "document_end"
}
],
"permissions": [
"tabs",
"storage",
"background",
"*://mail.google.com/*",
"*://*/*"
],
"browser_action": {
"default_icon": "img/icon.png",
"default_popup": "popup.html"
},
"web_accessible_resources" : [
"writeForm.js",
"disp.js",
"/calendar/jsDatePick.min.1.3.js",
"/calendar/jsDatePick_ltr.min.css",
"lib/gmailr.js",
"lib/jquery-bbq/jquery.ba-bbq.min.js",
"content.js",
"main.js",
"background.js"
]
}
This is main.js:
Gmailr.init(function(G) {
sender = G.emailAddress();
G.insertTop($("<div id='gmailr'><span></span> <span id='status'></span>)");
el = document.getElementById("testid");
el.addEventListener('click', mg, false);
var status = function(msg) {
G.$('#gmailr #status').html(msg); };
G.observe(Gmailr.EVENT_COMPOSE, function(details) {
....
status(" user: " + user);
console.log('user:', user);
//now try to send a message to the background page
//this always returns the error that method sendMessage does not exist for undefined
chrome.runtime.sendMessage({greeting: "test from gmailr"}, function(response) {
console.log("did it send?");
});
});
});
gmailr.js is quite long and is also not my own code but it can be seen here: http://pastebin.com/pK4EG9vh
Hi perhaps 3 likely reason to your problem :
The way you send messages to bgp from main.js and gmailr.js are perhaps wrong because you must arrive to communicate from any content script to your bgp. (in your manifest content script key the gmailr.js is missing). Show us your code it would help.
You seems to have a problem with the moment you search from content.js to access to the element created in main.js. Do you try to access your element with the jQuery $("").on() method ? A simple test must be to declare a function in one cs and to use it in another. If it's not working it's a manifest problem. The order you declare .js file in manifest content script key is important also.
try to in the manifest content script array "run_at":"document_end"
Hope it help !

Categories

Resources