Running chrome extension process while popup is closed - javascript

Basically I am trying to create an Auto Visitor Extension for Chrome to open a website's URL after some specific time. When I open the popup everything works fine but when the popup is close nothing works. I am trying to find out a method to run that Auto Visitor Extension even when the popup is close I have read multiple questions regarding this phenomena on Stack Overflow but none of them clarifies what I am looking for.
Here is my manifest file:
manifest.json
{
"manifest_version": 2,
"name": "Auto Visitor",
"description": "This extension will visit multiple pages you saved in extension",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": [
"background.js"
],
"persistent": false
},
"permissions": [
"activeTab",
"storage",
"tabs",
"http://*/",
"https://*/"
]
}
The background file that i want to run even when popup is close :
background.js
// this will work only when you denie the background script in manifest
chrome.runtime.onInstalled.addListener(function(details) {
var initTime = 5;
chrome.storage.local.set({"avtime": initTime}, function() {});
});
reloadMainTab();
function reloadMainTab() {
chrome.storage.local.get('avurl', function (result) {
var urlsToLoad = result.avurl;
console.log(urlsToLoad);
if(urlsToLoad==undefined){
// do nothing
}else{
var urlsArr = urlsToLoad.split(",");
chrome.storage.local.get('avtime', function (result) {
var thisTime = result.avtime;
/*
setting it to -1 because it gets incremented by 1
when it goes into getSelected method
*/
var index=-1;
setInterval(function(){
if(index < urlsArr.length-1){
chrome.tabs.getSelected(function (tab) {
// console.log('index in get selected'+index)
chrome.tabs.update(tab.id,{url: urlsArr[index]});
});
index++;
}else{
index=-1;
}
}, thisTime+"000");
});
}
});
}
any help would be really appreciated

Related

Content Script fails to run when navigating to a new link

I am currently writing a Google chrome extension that needs to run on YouTube videos. I have a content script which is a JavaScript file that does all the work I need it to do.
It is working fine, the only caveat is that for some reason, whenever you click a link to go to a new video, it doesn't run the JavaScript code immediately; you need to reload the page to make it work.
manifest.json
{
"name": "Title",
"description": "description",
"version": "0.5",
"permissions": [
"webNavigation",
"activeTab",
"tabs",
"*://*.youtube.com/*"
],
"browser_action": {
"default_icon": {
"16": "image.png"
},
"default_title": "name",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["*://*.youtube.com/*"],
"js": ["blocker.js"],
"run_at": "document_end"
}
],
"manifest_version": 2
}
blocker.js
myfunction();
function myfunction(){
//manipulate the HTML DOM
}
myfunction();
function myfunction(){
//manipulate the HTML DOM
}
You can put a time interval to detect that the URL changes
var currentURL = location.href;
setInterval(function() {
if(location.href != currentURL) {
myfunction();
currentURL = location.href
}
}, 100);
but I use this
var currentURL = location.href;
window.onclick=function(){
if(currentURL!==location.href){
myfunction();
currentURL = location.href
/*some code*/
}
}
HTML5 introduces a hashchange event which allows you to register for notifications of url hash changes without polling for them with a timer.
window.onhashchange = function (event) {
console.log(location.hash, event.oldURL, event.newURL);
myfunction();
}

Running a function in chrome extension on double click/select of a word

I am trying to fire a notification whenever I double click on a word/select it. Found several examples online but I still cannot get my example working:
Manifest:
{
"name": "hh",
"description": "hh!",
"manifest_version": 2,
"version": "0.0.0.1",
"content_scripts": [
{
"matches": [ "http://*/*", "https://*/*" ],
"js": [ "background.js" ],
"all_frames": true,
"run_at": "document_end"
}
],
"permissions": ["storage", "notifications"],
"icons": { "128": "neoprice.png" }
}
background.js
var listener = function(evt) {
var selection = window.getSelection();
if (selection.rangeCount > 0) {
displayPrice();
var range = selection.getRangeAt(0);
var text = range.cloneContents().textContent;
console.log(text);
}
};
document.addEventListener('dblclick', listener);
function displayPrice(){
chrome.notifications.create(getNotificationId(), {
title: "message.data.name",
iconUrl: 'hh.png',
type: 'basic',
message: "message.data.prompt"
}, function() {});
}
// Returns a new notification ID used in the notification.
function getNotificationId() {
var id = Math.floor(Math.random() * 9007199254740992) + 1;
return id.toString();
}
I was earlier adding the following but I saw people weren't using it, so I removed it
"app": {
"background": {
"scripts": ["background.js", "assets/jquery.min.js"]
}
},
What I am trying to achieve: Whenever they go to ANY page on selecting a word, it fires the function. Later, I wish to use this for a specific page. :)
Tried: How to keep the eventlistener real time for chrome extensions?
Chrome extension double click on a word
https://github.com/max99x/inline-search-chrome-ext
Both don't really work as I want them too. :(
Solution
It seems you are confused with background page and content script. Your background.js is a content script in fact, though its name is "background". While chrome.notifications api can be only called in background page, trying commenting displayPrice function will make your code work.
Next step
Take a look at above tutorials, wdblclick event triggers, use Message Passing to communicate with background page and call chrome.notications api in background page.
What's more
The following code is used in chrome apps rather than chrome extension.
"app": {
"background": {
"scripts": ["background.js", "assets/jquery.min.js"]
}
},

Javascript DOM Chrome Extension simple Script

I made an Extension for Firefox that random check all radio buttons & checkboxes on a website. Now I will make it for Chrome.
JS (inject.js):
function randomFromTo(from, to){
return Math.floor(Math.random() * (to - from + 1) + from);
}
function autoFill () {
for (i = 0; i < document.forms.length ;i++) {
for (j = 0; j < document.forms[i].length ;j++) {
if (document.forms[i].elements[j].type == "radio") {
start = j;
lastName = document.forms[i].elements[j].name;
while (j < document.forms[i].length - 1 && lastName == document.forms[i].elements[j+1].name) {
j++;
}
rand = randomFromTo(start, j);
document.forms[i].elements[rand].checked = true;
}
if (document.forms[i].elements[j].type == "checkbox") {
start = j;
lastName = document.forms[i].elements[j].name;
while (j < document.forms[i].length - 1 && lastName == document.forms[i].elements[j+1].name) {
j++;
}
rand = randomFromTo(start, j);
document.forms[i].elements[rand].checked = true;
}
}
}
}
autoFill();
So I read a lot about inject.js and Content Scripts so I tried both. And made it like this.
{
"name": "Auto Check Radio \u0026 Checkbox",
"version": "0.0.1",
"manifest_version": 2,
"description": "",
"homepage_url": "",
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"default_locale": "en",
"background": {
"page": "src/bg/background.html",
"persistent": true
},
"browser_action": {
"default_icon": "icons/icon16.png",
"default_title": "Autocheck",
"default_popup": "src/browser_action/browser_action.html"
},
"permissions": [
"tabs",
"notifications",
"http://*/",
"http://*/*",
"https://*/*"
],
"content_scripts": [{
"matches": ["https://*/*", "http://*/*"],
"js": ["src/inject/inject.js"],
"run_at": "document_end"
}],
"web_accessible_resources": ["src/inject/inject.js"],
"js": ["src/inject/inject.js"]
}
]
}
But I've got no idea how I can run the code. On Firefox it is much easier.
I don't need any background.html or browser_action.html
I only want to run the script - in the current tab - by clicking the icon.
Chould anyone give me a tip where i place my script?
Please read the Overview document first. Especially the Architecture part.
Any code that interacts with the page DOM must be in a Content Script. You've already put the code in src/inject.js.
Now, you don't need any UI to pop up when you click the button, so drop the "default_popup" item from the manifest and its HTML.
You also don't want your code to randomly execute when a tab loads. That's what "content_scripts" section in the manifest is about, so simply delete it.
Finally, you don't need a background HTML file. They have been replaced by autogenerated pages that are built from a list of scripts. So:
"background": {
"scripts": ["src/bg/background.js"]
},
"browser_action": {
"default_icon": "icons/icon16.png",
"default_title": "Autocheck"
},
Now, the only job of the background script is to register a handler for the button click. This is done through browserAction API:
// src/bg/background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id, {file: "src/inject/inject.js"});
});
That's it, at this point it should work.
Now, to trim down the fat.
You don't need a persistent background page, since all it does is keeping simple event listeners that don't save any kind of state information. You can safely add "persistent": false to the manifest.
Your permissions are a massive overkill. There's a handy activeTab permission that gives you access to the current page if your code is invoked by, say, browser action button press.
In fact, that is the only permission your code needs. It will take care of executeScript call.
"permissions" : ["activeTab"],

Google Chrome Tabs Execute Script

I'm trying to develop a google chrome extension that scrape out specific data from the page once the page is finished loading. I'm trying to achieve it by executing a javascript file by setting file : 'js/scrape.js' and runAt: 'document_idle'.
However, setting selected : false does work but selected : true doesn't.
index.js:
var crawler = function() {
return {
init : function() {
document.getElementById('open').addEventListener('click', this.open);
},
open : function() {
var url = document.getElementById('url').value;
chrome.tabs.create({
url : url,
selected : true //doesn't work, setting to false does work
}, function(tab) {
chrome.tabs.executeScript(tab.id, {
file : 'js/scrape.js',
runAt : 'document_idle'
});
});
}
}}()
document.addEventListener('DOMContentLoaded', function() {
crawler.init();
});
I included index.js inside popup.html:
<script type="text/javascript" src="index.js"></script>
Finally, manifest.json:
{
"manifest_version": 2,
"name": "Crawler",
"description": "Scrape out the crap.",
"version": "1.0",
"permissions": ["tabs", "http://*/*", "https://*/*"],
"browser_action": {
"default_title": "Scrape out the crap",
"default_icon": "icon.png",
"default_popup": "popup.html"
}
}
Using active => true fixed the issue. I missed the part of the documentation that explains it.

chrome.windows.onFocusChanged.addListener fired when closing Chrome, crashing plugin

I am writing a chrome extension, it uses chrome.windows.onFocusChanged.addListener to execute a content script. This works fine as long as I switch between different chrome windows however, the Listener is also fired when Chrome is closed. In that case the code inside the function leads to a crash of the extension.
I tried chacking for undefined, but that does not seem to be the issue.
The code lookls liks this
chrome.windows.onFocusChanged.addListener(function()
{
var ctab = chrome.tabs.getCurrent;
if(typeof ctab === "undefined")
{
}
else
{
chrome.tabs.executeScript(ctab.id,{file:"inject.js"}); //THIS LINE CRASHES THE APP WHEN I CLOSE THE BROWSER
}
});
I have a similar problem with a scheduled allert, which also executes the script (which leads to a crash when I close the browser between scheduling and execution).
function onAlarm(alarm)
{
if (alarm && alarm.name == 'check')
{
var ctab = chrome.tabs.getCurrent;
chrome.tabs.executeScript(ctab.id,{file:"inject.js"}); //CRASH
//more code...
Does anybody know how to avoid this crash?
Edit: Working Example
manifest.json
{
"name": "Rest Extension",
"description": "Set an Artnet Controler to the background collor",
"manifest_version": 2,
"version": "1",
"permissions": ["tabs", "http://*/*", "https://*/*", "background", "alarms"],
"background": {"scripts": ["background.js"]},
"content_scripts": [{"matches": ["http://*/*", "https://*/*"],"js": ["inject.js"]}],
"browser_action":
{
"default_icon": "16x16.png",
"default_popup": "popup.html"
}
}
background.js
chrome.windows.onFocusChanged.addListener(function()
{
var ctab = chrome.tabs.getCurrent;
if(typeof ctab === "undefined")
{
}
else
{
chrome.tabs.executeScript(ctab.id,{file:"inject.js"}); //THIS LINE CRASHES THE APP WHEN I CLOSE THE BROWSER
}
})
all the other files can be empty (including the inject.js)
chrome.tabs.getCurrent is a method: it's not an instance of a Tab object.
You should try this:
chrome.windows.onFocusChanged.addListener(function()
{
chrome.tabs.getCurrent(function(ctab)
{
chrome.tabs.executeScript(ctab.id, { file: "inject.js" });
});
});
Reference: http://developer.chrome.com/extensions/tabs.html#method-getCurrent

Categories

Resources