Auto start chrome extension - javascript

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.

Related

Communication between background.js and content-script? Response is UNDEFINED

From content-script:
chrome.runtime.sendMessage({ type: "getFormatOption" }, function (response) {
return response === 'csv';
});
I have inspected in console: the value, which is used in SendResponse() from background.js method is OK. The problem is that response is always UNDEFINED. What am I doing wrong?
background.js:
chrome.runtime.onMessage.addListener(
function (message, sender, sendResponse) {
switch (message.type) {
case 'getFormatOption':
var response = $('input[name=csvOrEnter_radio]:checked', '#csvOrEnter_form').val();
console.log('formatOption: ' + response);
sendResponse(response);
break;
case 'getFilteringStrategy':
var response = $('input[name=filteringStrategy_radio]:checked', '#filteringStrategy_form').val();
console.log('filteringStrategy: ' + response);
sendResponse(response);
break;
default:
console.error('Unrecognised message: ', message);
}
}
);
The idea that I take some values from radiobuttons from my plugin popup.html.
Manifest:
{
// default for the latest version of Chrome extensions
"manifest_version": 2,
// extension related general info
"name": "FB Interest Search Tool",
"short_name": "FB Interest Search Tool",
"description": "FB Interest Search Tool",
"version": "1.0.0",
"default_locale": "en",
// sets path to popup files
"browser_action": {
"default_icon": "img/128.png",
"default_popup": "popups/popup.html",
"default_title": "FB Interest Search Tool"
},
// sets path to content scripts and when they are injected onto the page
"content_scripts": [
{
"matches": [ "http://*/*", "https://*/*" ],
"css": [ "styles/styles.css" ],
"js": [
"bower_components/jquery.min.js",
"bower_components/jquery.cookie.js"
]
}
],
// sets path to background scripts
"background": {
"scripts": [
"bower_components/jquery.min.js",
"bower_components/jquery.cookie.js",
"bg/background.js",
"content-scripts/rewriteStorage.js"
]
},
"permissions": [
"activeTab",
"http://*/",
"https://*/",
"file:///*/*",
"<all_urls>",
"tabs",
"storage",
"unlimitedStorage",
"storage",
"cookies"
],
"web_accessible_resources": [ "styles/commentblocker_on.css" ]
}
Problem 1: it's called background.js.
I'm not even remotely joking. Well maybe a little.
Since it's included BOTH in the popup and as a background script, there are 2 message listeners registered. And only one can answer:
Note: If multiple pages are listening for onMessage events, only the first to call sendResponse() for a particular event will succeed in sending the response. All other responses to that event will be ignored.
Guess which gets to answer first? My bets are on the background, since it registered the listener first.
While you still see the listener execute in the popup if you try to debug, its sendResponse is ignored because the background already answered.
This one's easy to fix: make a copy, call it popup.js, and keep only relevant logic in both. Don't include the same file in both places unless you're 100% certain code needs to run in both.
Problem 2: Popup is mortal.
When the popup is closed — it's dead, Jim. It simply does not exist: neither the listener, nor the radiobuttons. Therefore, it cannot answer the message.
Fixing this requires reworking the architecture. The only 2 places that can provide storage you can query at any time are:
Background page. It needs to hold the state in a way other than selected element, and the popup needs to inform about the change of state.
chrome.storage API. Both the popup and the content script can read/write to it.
For options, the second one is preferable.

Connect external js lib to chrome event page

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?

Chrome Extension: how to change JS url before he starts loading

I wanna change src of js javascript before he starts loading using a Chrome Extension.
Manifest.json
{
"name":"Inject DOM",
"version":"1",
"manifest_version":2,
"permissions": [
"webRequest",
"webNavigation",
"http://*/*",
"https://*/*"
],
"content_scripts": [
{
"run_at": "document_end",
"matches": ["http://www.example.com/*"],
"js": ["inject_this.js"]
}
]
}
inject_this.js
I execute this code in various functions scenarios
var element = event.srcElement;
if(/production_path/.test(element.src)){
element.src = element.src.replace(/production_url/gi, "dev_path");
}
Scenario A
document.addEventListener('DOMNodeInserted', nodeInsertedCallback);
Scenario B
Executing this scenario into inject_this.js throw this TypeError:
Uncaught TypeError: Cannot read property 'onBeforeRequest' of undefined
Executing this in another js doesn't work
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
if(/production_url/.test(details.url)){
return {
redirectUrl: details.usl.replace(/production_url/gi, "dev_url")
}
}
},
{urls: ["<all_urls>"]},
["blocking"]);
Where do i put this snippet code ?
Scenario C
document.addEventListener('beforeload', doBeforeLoad , true);
but every time script.src is changed too late, the resource is loaded.
How can I change javascript url before he starts loading?
Your solution B should work.
Two conditions need to be met for this to work:
This code should go to a background script / event page.
You need appropriate permissions: "webRequest", "webRequestBlocking"
You probably also should not use it on <all_urls>, since your extension seems to be specific to a single site (from your manifest). Doing it on all URLs is going to slow your Chrome down and may lead to breaking other sites, consider using a restrictive match pattern like "http://www.example.com/*production_url*"

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

develop screenshot chrome extension

i saw a lot of answers here but no one is what i'm looking for.
i want to take screenshot from chrome extension just for the screen i see at the first time without scrolling the page.
and "alert" the created file base64 path.
i have all the right permissions:
"permissions": [
"activeTab",
"tabs" ,
"storage",
"unlimitedStorage",
"browsingData",
"notifications",
"http://*/*",
"https://*/*",
"file://*/*",
"background" // added after i got the answer
],
"background": { // added after i got the answer
"scripts": [
"js/background.js"
]
},
in my manifest.json
i also have the code:
$(document).ready(function() {
alert("1");
chrome.tabs.captureVisibleTab(null, {}, function (image) {
alert("2");
});
});
i got 1 all the time but 2 i never get and i don't know why. please help..
thanks ..
UPDATE
that's the missing part (background.js)
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
chrome.tabs.captureVisibleTab(
null,
{},
function(dataUrl){
sendResponse({imgSrc:dataUrl});
}); //remember that captureVisibleTab() is a statement
return true;
}
);
and then :
chrome.tabs.captureVisibleTab(null, {}, function (image) {
// alert("2");
alert(response.imgSrc);
});
You can't do extension API call in content script.Try to use use message passing if you really want to trigger this function in content script.
And please note that the permission requirement of tabs.captureVisibleTab() has been updated since chrome rev.246766.
Extension need to have '< all_urls >' permission, or been granted the
'activeTab' permission to be allowed to use tabs.captureVisibleTab().
Developer doc doesn't mention it.
manifest.json
"permissions": [
"activeTab",
"tabs" ,
"storage",
"unlimitedStorage",
"browsingData",
"notifications",
"http://*/*",
"https://*/*",
"file://*/*",
"<all_urls>"
]
Try to execute this code below in background page and screenshot capturing will work as expected.
chrome.tabs.captureVisibleTab(null,{},function(dataUri){
console.log(dataUri);
});
screenshot
It actually does not work on Google pages as on the Extensions page, were it looks very natural to test your extension while developing.
(Should be a way to test that before taking the snapshot, I think...)

Categories

Resources