I added the click event listener in a working sample app (pageAction) but I have no idea where has gone wrong. Take a look at 2 of this file:
my manifest json
{
"name" : "Page action by content",
"version" : "1.1",
"description" : "Shows a page action for HTML pages containing a video",
"background" : {
"scripts": ["background.js"],
"persistent": false
},
"page_action" :
{
"default_icon" : "video-19.png",
"default_title" : "There's a <video> in this page!"
},
"permissions": [ "declarativeContent" ],
"icons" : {
"48" : "video-48.png",
"128" : "video-128.png"
},
"manifest_version": 2
}
background js
chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([{
conditions: [
// When a page contains a <video> tag...
new chrome.declarativeContent.PageStateMatcher({
css: ["video"]
})
],
// ... show the page action.
actions: [new chrome.declarativeContent.ShowPageAction() ]
}]);
});
});
chrome.pageAction.onClicked.addListener(function(tab) {
console.log('Turning ' + tab.url + ' red!');
chrome.tabs.executeScript({
code: 'document.body.style.backgroundColor="red"'
});
});
I even put the click function within chrome.runtime, nothing happen. I don't think I forgot to reload the extension pack.
Seems you cannot access the content of the active tab, hence your chrome.tabs.executeScript failed.
Try to acquire "activeTab" permission in addition.
Related
window.open(".....")
chrome.cookies.getAll({domain: "......"}, function(cookies) {
for(var i=0; i<cookies.length;i++) {
chrome.cookies.remove({url: "......", name: "STX_SESSION"});
}})
chrome.tabs.reload()
window.open(".....")
const interval = setInterval(function() {
chrome.cookies.getAll({domain: "....."}, function(cookies) {
for(var i=0; i<cookies.length;i++) {
chrome.cookies.remove({url: ".....", name: "STX_SESSION"});
}})
chrome.tabs.reload()
window.open("......")
}, 1200000);
})
manifest.json
{
"name" : "....",
"version" : "1.0",
"description" : "....",
"permissions": [ "cookies", "tabs", "<all_urls>" , "http://*/", "https://*/"],
"icons": { "16": "....", "48": ".....", "128": "...." },
"browser_action": {
"default_icon": "....."
},
"background": {
"scripts": ["script.js"]
},
"manifest_version": 2
}
This is my code. I would like to reset the interval or in other word stop the background script from running. Is it possible to do this by clicking on the extension icon?
You cannot stop the background script since you've used the default value for persistent but you can stop the interval.
You can add a click event listener to the extension's icon using:
chrome.browserAction.onClicked.addListener(() => { .. });
And to stop the interval use clearInterval(interval).
Here is a complete solution:
chrome.browserAction.onClicked.addListener(() => clearInterval(interval));
In order for all this to work, you'll have to add browser_action to the permissions array in the manifest and make sure, the browser_action key doesn't have a default_popup key-value pair.
All in all, you should be using "manifest_version": 3 I think manifest version 2 extension are no longer accepted for publishing on the Google Web Store.
Based on your comment, it seems that you want to toggle the interval on click, here is how you can do that (along with some refactoring):
function doStuff() {
chrome.cookies.getAll({domain: "......"}, function(cookies) {
for(var i=0; i<cookies.length;i++) {
chrome.cookies.remove({url: "......", name: "STX_SESSION"});
}
});
chrome.tabs.reload()
}
doStuff();
window.open(".....")
const interval = setInterval(doStuff, 1200000);
chrome.browserAction.onClicked.addListener(() => {
if (interval === null) {
interval = setInterval(doStuff, 1200000);
} else {
clearInterval(interval)
interval = null;
}
});
Overflow Developes: I have search a lot about the textarea selection but have't found the proper solution.
Goal: I am going to build my own extension in which I want to perform some functionality. I have accessed the DOM. And further cannot able to access the only textarea.
Required: enter image description here I Want this type of working in my extension.
manifest.json
{
"manifest_version": 2,
"name": "DOM",
"version": "0.0",
"background": {
"persistent": false,
"scripts": [
"background.js"
]
},
"content_scripts": [
{
"matches": [
"*://*.stackoverflow.com/*"
],
"js": [
"content.js"
]
}
],
"browser_action": {
"default_title": "DOM",
"default_popup": "index.html"
},
"permissions": [
"activeTab",
"tabs",
"<all_urls>"
]}
index.html
<!DOCTYPE html>
<html>
<head>Fayzan</head>
<body> <button id="test">DOM!</button>
<script src="test.js"></script>
</body>
</html>
Content.js
// Listen for messages
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
// If the received message has the expected format...
if (msg.text === 'report_back') {
// Call the specified callback, passing
// the web-page's DOM content as argument
sendResponse(document.all[0].outerHTML);
}
});
background.js
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?stackoverflow\.com/;
function doStuffWithDom(domContent) {
console.log('I received the following DOM content:\n' + domContent);
} // When the browser-action button is clicked...
chrome.browserAction.onClicked.addListener(function(tab) { // ...check the URL of the active tab against our pattern and...
if (urlRegex.test(tab.url)) { // ...if it matches, send a message specifying a callback too
chrome.tabs.sendMessage(tab.id, {
text: 'report_back'
}, doStuffWithDom);
}
});
test.js
document.getElementById("test").addEventListener('click', () => {
alert("DOM POPUP");
function modifyDOM() {
console.log('Tab script:');
console.log(document.body);
return document.body.innerHTML;
}
chrome.tabs.executeScript({
code: '(' + modifyDOM + ')();'
},
(results) => {
console.log("fayzan bhatti");
console.log(results);
}
);
});
I'm attempting to create a Chrome extension which will add a parameter to the end of a URL if the URL matches a given pattern (*://*.mydomain.com/s/*). Below is the manifest file and background script I have, but I cannot get it working. What am I doing wrong?
manifest.json:
{
"manifest_version": 2,
"name": "Search Grid View",
"version": "0.1",
"description": "Changes MyDomain.com search to grid view by default",
"background": {
"scripts": ["background.js"]
},
"permissions": [
"tabs",
"webRequest",
"*://*.mydomain.com/s/*",
"webRequestBlocking"
]
}
background.js:
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
var currentUrl = tabs[0].url;
var newUrl = currentUrl + "&style=gridview"
return { redirectUrl: newUrl};
},
{
urls: [
'*://*.mydomain.com/s/*'
],
types: ['main_frame']
},
['blocking']);
Thanks in advance for any advice!
Use debugger - click your extension's background page on chrome://extensions page and switch to the Sources panel.
To obtain the url use onBeforeRequest's callback parameter
Check if the url is already modified.
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
return {
redirectUrl: details.url +
(details.url.indexOf("?") == -1 ? "?" : "") +
(details.url.indexOf("&style=gridview") == -1 ? "&style=gridview" : "")
};
},
{urls: ['*://*.mydomain.com/s/*'], types: ['main_frame']},
['blocking']
);
I'm trying to remove the cache when the user go to this url stackoverflow.com/?clear then reload and go to stackoverflow.com with a clean cache, I tried a many methods but I failed.
Here is my last attempt, It's not affect the cache at all!
Manifest Code
{
"name": "stackoverflow",
"version": "1.0",
"background": {
"scripts": ["jquery.js","background.js"],
"persistent": false
},
"page_action" :
{
"default_icon" : "icon.png",
"default_title" : "Remove"
},
"permissions" : [
"declarativeContent", "browsingData", "tabs"
],
"manifest_version": 2
}
background.js
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 contains a 'stackoverflow.com/?clea' ...
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlContains: 'stackoverflow.com/?clear' },
})
],
// And shows the extension's page action.
actions: [ new chrome.declarativeContent.ShowPageAction() ]
}
]);
});
});
function clearMe(tab) {
var ms = (30 * 60) * 1000; // 30 minutes
var time = Date.now() - ms;
chrome.browsingData.removeCache({"since": time}, function() {
chrome.tabs.update({url: 'http://stackoverflow.com'});
});
}
//It will be perfect if user do not have to click
chrome.pageAction.onClicked.addListener(clearMe)
I need better alternative to remove cache without even the user click a button.
tabs api should be enough for this. Here's how you should do it. I've tested it and it's working fine.
Manifest Code
{
"name": "stackoverflow",
"version": "1.0",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"permissions" : [
"tabs", "browsingData"
],
"manifest_version": 2
}
background.js
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
// if url is changed
if (changeInfo.url) {
var url = changeInfo.url;
if (url.indexOf("stackoverflow.com/?clear") != -1) {
alert("Clearing cache...");
clearMe(tab);
}
}
});
function clearMe(tab) {
var ms = (30 * 60) * 1000; // 30 minutes
var time = Date.now() - ms;
chrome.browsingData.removeCache({"since": time}, function() {
chrome.tabs.update(tab.id, { url: 'http://stackoverflow.com' });
});
}
I am making a chrome extension to sign into a wifi system, and currently have it set so that they must click on the extension to sign in. But instead I want it to just sign them in every 30 minutes, using background js I want it to check a cookie I saved if 30 minutes has passed and then sign in. But instead it only works when you first install it.
Here is my manifest.json:
{
"manifest_version": 2,
"name": "BCA Auto Login",
"description": "This extension automatically signs you into the BCA wifi",
"version": "1.0",
"permissions": [ "cookies", "http://*/*", "https://*/*" ],
"content_scripts": [{
"matches": ["http://*/*","https://*/*"],
"js": ["jquery.js","login.js"]
}],
"background": {
"scripts": ["jquery.js", "background.js"]
},
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
}
}
Here is my background.js:
$(document).ready(function(){
chrome.cookies.get({ url: 'urlofCookie.com', name: 'time' },
//the cookie is a time in minutes
function (cookie) {
if (cookie) {
var current = new Date();
if((current.getMinutes() - cookie) >= 30){
$.ajax({
type : 'POST',
url : 'https://signinURL',
data : {
username: 'username',
password: 'password',
},
success : workedFunction
});
}
}
else{
cookieNotFound();
}
});
});
You only call the function on page load, so no wonder it does not execute after that. If you want to perform an action periodically, you can use the chrome.alarms API and create an alarm to fire every 30 minutes (you don't even need the cookie unless you use it for other things as well).
E.g.:
var wifiAlarmName = "wifiSignIn";
chrome.alarms.create(wifiAlarmName, {
delayInMinutes: 0,
periodInMinutes: 30
});
chrome.alarms.onAlarm.addListener(function(alarm) {
if (alarm.name === wifiAlarmName) {
// Sign in
...
}
});