How do I stop content script execution in the current tab? - javascript

I'm working on a Google Chrome Extension, and I'm encountering a bug I can't solve on my own.
It works as expected switching to Youtube's Dark Mode on a single Youtube tab, but if you're on Youtube and Ctrl/Cmd click a link (open in a new tab), content.js is triggered again and the current tab is turned white and the new tab is dark.
If you are in a dark tab, a "child" tab should automatically be dark.
manifest.json:
{
"manifest_version": 2,
"permissions": [
"https://www.youtube.com/*",
"activeTab"
],
"background": {
"scripts": ["background.js"],
"persistant": false
},
"browser_action": {
"default_title": "Engage Youtube Dark Mode."
},
"content_scripts": [
{
"matches": ["https://www.youtube.com/*"],
"js": ["content.js"]
}]
}
background.js:
//var alreadyTriggered = false;
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "clicker.js"});
});
/*
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
alreadyTriggered = false;
});*/
chrome.runtime.onMessage.addListener(function(response, sender, sendResponse) {
//if (!alreadyTriggered) {
chrome.tabs.executeScript(null, {file: "clicker.js"});
//alreadyTriggered = true;
//};
return true;
});
content.js:
var myDate = new Date();
if ((myDate.getHours() <= 7) || (myDate.getHours() >= 19))
{
var darkMode = document.body.getAttribute("dark");
if (!darkMode) {
chrome.runtime.sendMessage(window.location.href, function(result) {});
};
};
I'm guessing that I'm using activeTab incorrectly. Any help would be greatly appreciated. Thanks!
clicker.js:
stepOne();
function stepOne() {
try {
var buttons = document.querySelectorAll("button.ytd-topbar-menu-button-renderer");
buttons[0].click();
stepTwo();
}
catch(error) {
setTimeout(stepOne, 250);
}
}
function stepTwo() {
try {
buttons = document.querySelectorAll("paper-item.ytd-account-settings");
buttons[0].click();
stepThree();
}
catch(error) {
setTimeout(stepTwo, 100);
}
}
function stepThree() {
try {
buttons = document.querySelectorAll("paper-toggle-button.style-scope.ytd-account-settings");
buttons[0].click();
document.body.click();
}
catch(error) {
setTimeout(stepThree, 100);
}
}

What ended up working for me was to use a combination of:
using window.onload = doStuff();
And to make sure that the value for darkMode was null, not undefined.
Hopefully this helps someone who's been endlessly tweaking their code.

Related

Chrome extension crashes when trying to access from two different windows?

I open a chrome extension, then open a new window (incognito for example) and try to open the extension again, it crashes. I then need to reload the app through the chrome extensions page. There are no errors in this.
The question is how can I work with the extension from different windows at the same time
{
"manifest_version": 2,
"name": "Such Activity",
"description": "Wow",
"version": "1.0",
"permissions": ["tabs","webRequest", "webRequestBlocking", "storage", "http://*/","https://*/"],
"browser_action": {
"default_title": "Click Me",
"default_popup": "popup.html",
"default_icon": "start.png"
}
}
and my popup.js
function injectTheScript() {
console.log("start script")
if (nfts.length <= 0) {
console.log("successfull")
return;
}
id = nfts.pop()
var newURL = "url"+id;
chrome.tabs.update({url: newURL}, myTab => {
function listener(tabId, changeInfo, tab) {
if (tabId === myTab.id && changeInfo.status == 'complete') {
chrome.tabs.query({active: true, currentWindow: true}, tabs => {
chrome.tabs.executeScript(tab.id, {file: "content_script.js"});
})
counter++;
document.getElementById('count').textContent = counter
console.log("hoba"+counter)
setTimeout(injectTheScript, 7000);
}
};
if (!isInjected) {
chrome.tabs.onUpdated.addListener(listener);
isInjected = true;
}
});
}
document.getElementById('clickactivity').addEventListener('click', injectTheScript)
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
return { cancel: true };
},
{urls: ["*://*/*checkUser"]},
["blocking"]
);
the extension crashes before I interact with it. it crashes when i click on its icon in chrome
It's a bug in stable version Chrome, it's fixed in Chrome Canary
thx wOxxOm for

How can I make extension disabled when the link is not matched with content_script?

"content_scripts": [
{
"matches": [
"https://www.google.com/*"
],
"js": ["contentScript.bundle.js"],
"css": ["styles.css"]
}
],
How can I make extension turned off or not clickable if its not matched with content_script link?
You can implement something like this in the background file,
Steps
Create an Array of domains which has been specified in your content script.
Add a listener on the tab selection changed and tab updated.
Checkout the currently active tab is in your array or not.
Set a flag value true false using the above check.
On extension click now, check if the flag is true then perform the task else ignore the click.
let activeExtension = false;
const contentScriptMatchArray = ['https://www.google.com', 'https://www.youtube.com'];
chrome.tabs.onActivated.addListener(handleExtensionActiveState);
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
handleExtensionActiveState(tab);
});
function handleExtensionActiveState(tabs) {
if (tabs.tabId) {
chrome.tabs.get(tabs.tabId, (tab) => {
activeExtension = checkWhiteListedOrigin(tab);
});
} else {
activeExtension = checkWhiteListedOrigin(tabs);
}
}
function checkWhiteListedOrigin(tab) {
const tabURl = new URL(tab.url);
return contentScriptMatchArray.includes(tabURl.origin);
}
chrome.browserAction.onClicked.addListener(function () {
if (activeExtension) {
console.log('Clicked');
}
});
Note
you can also change your extension icon, so your extension will look like it's actually disabled
References
https://developer.chrome.com/docs/extensions/reference/tabs/#event-onActiveChanged

How To Call Chrome Extension Function After Page Redirect?

I am working on building a Javascript (in-browser) Instagram bot. However, I ran into a problem.
If you run this script, the first function will be called and the page will be redirected to "https://www.instagram.com/explore/tags/samplehashtag/" and the second function will be called immediately after (on the previous URL before the page changes to the new URL). Is there a way to make the second function be called after this second URL has been loaded completely?
I have tried setting it to a Window setInterval() Method for an extended time period, window.onload and a couple of other methods. However, I can't seem to get anything to work. Any chance someone has a solution?
This is my first chrome extension and my first real project, so I may be missing something simple..
manifest.json
{
"name": "Inject Me",
"version": "1.0",
"manifest_version": 2,
"description": "Injecting stuff",
"homepage_url": "http://danharper.me",
"background": {
"scripts": [
"background.js"
],
"persistent": true
},
"browser_action": {
"default_title": "Inject!"
},
"permissions": [
"https://*/*",
"http://*/*",
"tabs"
]
}
inject.js
(function() {
let findUrl = () => {
let hashtag = "explore/tags/samplehashtag/";
location.replace("https://www.instagram.com/" + hashtag);
}
findUrl();
})();
background.js
// this is the background code...
// listen for our browerAction to be clicked
chrome.browserAction.onClicked.addListener(function(tab) {
// for the current tab, inject the "inject.js" file & execute it
chrome.tabs.executeScript(tab.ib, {
file: 'inject.js'
});
});
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
chrome.tabs.executeScript(tab.ib, {
file: 'inject2.js'
});
});
inject2.js
(function() {
if (window.location.href.indexOf("https://www.instagram.com/explore/tags/samplehashtag/") != -1){
let likeAndRepeat = () => {
let counter = 0;
let grabPhoto = document.querySelector('._9AhH0');
grabPhoto.click();
let likeAndSkip = function() {
let heart = document.querySelector('.glyphsSpriteHeart__outline__24__grey_9.u-__7');
let arrow = document.querySelector('a.coreSpriteRightPaginationArrow');
if (heart) {
heart.click();
counter++;
console.log(`You have liked ${counter} photographs`)
}
arrow.click();
}
setInterval(likeAndSkip, 3000);
//alert('likeAndRepeat Inserted');
};
likeAndRepeat();
}
})();
It is not clear from the question and the example, when you want to run your function. But in chrome extension there is something called Message Passing
https://developer.chrome.com/extensions/messaging
With message passing you can pass messages from one file to another, and similarly listen for messages.
So as it looks from your use case, you can listen for a particular message and then fire your method.
For example
background.js
chrome.runtime.sendMessage({message: "FIRE_SOME_METHOD"})
popup.js
chrome.runtime.onMessage.addListener(
function(request) {
if (request.message == "FIRE_SOME_METHOD")
someMethod();
});
EDIT
Also if you want to listen for the URL changes, you can simply put a listener provided as in the documentation.
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
console.log('updated tab');
});

Tab Listener not Getting Activated by Message from Background Script

I am sending a message to the tab were I have a content script (getTradingData.js) from the background.js with the following code:
alert("Automated TradingView Extension is running");
chrome.tabs.query({
url: 'https://www.tradingview.com/*'
}, function(tabs) {
if (tabs.length == 1) {
chrome.tabs.sendMessage(tabs[0].id, {subject: "testConnection"}, function(response) {
alert(response); //THIS RETURNS UNDEFINED
if (response.msg == "getTradingDataScriptHere") {
alert("Script Already Injected. Do not reinject"); //THIS IS NOT RUNNING
} else {
chrome.tabs.executeScript(tabs[0].id, {file: "jquery-2.2.3.min.js"});
chrome.tabs.executeScript(tabs[0].id, {file: "jquery.waituntilexists.min.js"});
chrome.tabs.executeScript(tabs[0].id, {file: "getTradingData.js"});
alert("Injected all Nessessary Scripts for Auto Trading View to work"); //THIS IS NOT RUNNING
}
});
} else {
alert("Please have one and only one tradingview chart page opened.");
}
});
var price = "Waiting For Price"
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.subject == "getPrice") {
sendResponse({
price: price
});
} else if (request.from == "getTradingData" && request.subject == "scriptLoaded") {
//getTradingData.js Script has Fully Loaded onto Website
} else if (request.from == "getTradingData" && request.subject == "updatePrice") {
price = request.price
}
});
However the response return as undefined. So basically I am not getting a response back.
Here is what I have in my getTradingData.js that should respond to the message:
alert("getTradingData.js is Running");
//Send message to let the extension know the script has been injected on site
chrome.runtime.sendMessage({
from: 'getTradingData',
subject: 'scriptLoaded'
});
chrome.runtime.onConnect.addListener(function(port) { //THIS DOESN'T WORK EITHER
console.assert(port.name == "tradingdata");
port.onMessage.addListener(function(request) {
if (request.msg == "Knock knock")
port.postMessage({subject: "price"});
else if (msg.answer == "Madame")
port.postMessage({question: "Madame who?"});
else if (msg.answer == "Madame... Bovary")
port.postMessage({question: "I don't get it."});
});
});
//to check if script already injected
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
alert("got message"); //THIS IS NOT RUNNING
if (request.subject == "testConnection") {
sendResponse({msg: "getTradingDataScriptHere"});
}
});
//wait till item has loaded
$(".dl-header-figures").waitUntilExists(function(){
alert($(".dl-header-figures").text());
updatePrice();
});
function updatePrice(){
alert("updating price");
chrome.runtime.sendMessage({
from: 'getTradingData',
subject: 'updatePrice',
price: $(".dl-header-figures").text()
});
}
//TODO: Use long lived connections for this to work: https://developer.chrome.com/extensions/messaging
// setInterval(updatePrice(), 3000);
However this never gets activated, I never get the alert "got message".
Here is what my manifest.json looks like:
{
"manifest_version": 2,
"name": "Automated TradingView Strategy",
"description": "This extension shows a Google Image search result for the current page",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["jquery-2.2.3.min.js", "background.js"]
},
"content_scripts": [
{
"matches": ["https://www.tradingview.com/chart/*", "http://www.tradingview.com/*"],
"js": ["jquery-2.2.3.min.js", "jquery.waituntilexists.min.js", "getTradingData.js"]
}
],
"permissions": [
"activeTab",
"tabs",
"*://*.tradingview.com/*",
"https://ajax.googleapis.com/"
]
}
What am I doing wrong? How can I make it send a response back. Even when I refresh extension which should reload background.js without reloading tabs which already has the content script injected in it I get no response because the Listener is not activated.
What are you trying to do exactly in your background script?
chrome.tabs.query runs only once when you load the extension, also, the scripts you are injecting with chrome.tabs.executeScript should be injected already because of the manifest.
I don't know exactly what you're trying to do, but, you can listen to an event every time a tab is updated (tabs are updated after being created) - chrome.tabs.onUpdated.addListener
Updated background.js:
alert("Automated TradingView Extension is running");
chrome.tabs.query({
url: 'https://www.tradingview.com/*'
}, function(tabs) {
console.log(tabs);
if (tabs.length == 1) {
chrome.tabs.sendMessage(tabs[0].id, {subject: "testConnection"}, function(response) {
if (response) {
alert("Script Already Injected. Do not reinject");
} else {
chrome.tabs.executeScript(tabs[0].id, {file: "jquery-2.2.3.min.js"});
chrome.tabs.executeScript(tabs[0].id, {file: "jquery.waituntilexists.min.js"});
chrome.tabs.executeScript(tabs[0].id, {file: "getTradingData.js"});
alert("Injected all Nessessary Scripts for Auto Trading View to work");
}
});
} else {
alert("Please have one and only one tradingview chart page opened.");
}
});
var price = "Waiting For Price"
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.subject == "getPrice") {
sendResponse({
price: price
});
} else if (request.from == "getTradingData" && request.subject == "scriptLoaded") {
//getTradingData.js Script has Fully Loaded onto Website
} else if (request.from == "getTradingData" && request.subject == "updatePrice") {
price = request.price
}
});

Remember state chrome extension

I use a chrome extension to fire two content scripts to inject css. If the user opens the page the contentscript-on.js loads (defined in my manifest.json):
manifest.json
{
"name": "tools",
"version": "1.1",
"description": "tools",
"browser_action": {
"default_icon": "icon-on.png",
"default_title": "tools"
},
"manifest_version": 2,
"content_scripts": [
{
"matches": [ "*://*/*" ],
"include_globs": [ "*://app.example.*/*" ],
"js": ["jquery-1.11.0.min.js", "contentscript-on.js"]
}
],
"background": {
"scripts": ["background.js"],
"persistent": true
},
"permissions": [
"storage",
"https://*.app.example.de/*", "tabs", "webNavigation"
]
}
background.js
function getToggle(callback) { // expects function(value){...}
chrome.storage.local.get('toggle', function(data){
if(data.toggle === undefined) {
callback(true); // default value
} else {
callback(data.toggle);
}
});
}
function setToggle(value, callback){ // expects function(){...}
chrome.storage.local.set({toggle : value}, function(){
if(chrome.runtime.lastError) {
throw Error(chrome.runtime.lastError);
} else {
callback();
}
});
}
chrome.browserAction.onClicked.addListener( function(tab) {
getToggle(function(toggle){
toggle = !toggle;
setToggle(toggle, function(){
if(toggle){
//change the icon after pushed the icon to On
chrome.browserAction.setIcon({path: "icon-on.png", tabId:tab.id});
//start the content script to hide dashboard
chrome.tabs.executeScript({file:"contentscript-on.js"});
}
else{
//change the icon after pushed the icon to Off
chrome.browserAction.setIcon({path: "icon-off.png", tabId:tab.id});
//start the content script to hide dashboard
chrome.tabs.executeScript({file:"contentscript-off.js"});
}
});
});
});
contentscript-on.js
$(document).ready(function() {
chrome.storage.local.get('toggle', function(data) {
if (data.toggle === false) {
return;
} else {
// do some css inject
}
});
});
contentscript-off.js
$(document).ready(function() {
// set css to original
});
Everything works fine, but how can I save the "state" of the icon? If the user close the browser and open it again, the last used contentscript should load.
Thank you very much for your help.
You have two methods (at least), one is "old" and one is "new".
Old: localStorage
Your extension pages share a common localStorage object you can read/write, and it is persistent through browser restarts.
Working with it is synchronous:
var toggle;
if(localStorage.toggle === undefined){
localStorage.toggle = true;
}
toggle = localStorage.toggle;
chrome.browserAction.onClicked.addListener( function(tab) {
var toggle = !toggle;
localStorage.toggle = toggle;
/* The rest of your code; at this point toggle is saved */
});
It's simple to work with, but there are downsides: localStorage context is different for content scripts, so they need to communicate via Messaging to get the values from the background script; also, complications arise if the extension is used in Incognito mode.
New: chrome.storage API
To work with the new method, you need permission "storage" in the manifest (does not generate a warning).
Also, unlike localStorage, working with it is asynchronous, i.e. you will need to use callbacks:
function getToggle(callback) { // expects function(value){...}
chrome.storage.local.get('toggle', function(data){
if(data.toggle === undefined) {
callback(true); // default value
} else {
callback(data.toggle);
}
});
}
function setToggle(value, callback){ // expects function(){...}
chrome.storage.local.set({toggle : value}, function(){
if(chrome.runtime.lastError) {
throw Error(chrome.runtime.lastError);
} else {
callback();
}
});
}
chrome.browserAction.onClicked.addListener( function(tab) {
getToggle(function(toggle){
toggle = !toggle;
setToggle(toggle, function(){
/* The rest of your code; at this point toggle is saved */
});
});
});
Asynchronous code is a bit harder to work with, but you get some advantages. Namely, content scripts can use chrome.storage directly instead of communicating with the parent, you can watch for changes with onChanged, and you can use chrome.storage.sync instead of (or together with) chrome.storage.local to propagate changes to all browsers a user is logged into.
EDIT
I'm including a full solution, since the OP made a mistake of mixing per-tab state and global state.
contentscript.js
$(document).ready(function() {
chrome.storage.local.get('toggle', function(data) {
if (data.toggle === false) {
return;
} else {
/* do some css inject */
}
});
chrome.storage.onChanged.addListener(function(changes, areaName){
if(areaName == "local" && changes.toggle) {
if(changes.toggle.newValue) {
/* do some css inject */
} else {
/* set css to original */
}
}
});
});
background.js:
/* getToggle, setToggle as above */
function setIcon(value){
var path = (value)?"icon-on.png":"icon-off.png";
chrome.browserAction.setIcon({path: path});
}
getToggle(setIcon); // Initial state
chrome.browserAction.onClicked.addListener( function(tab) {
getToggle(function(toggle){
setToggle(!toggle, function(){
setIcon(!toggle);
});
});
});
This way, you only need one content script.

Categories

Resources