I've developed a Chrome extension that injects a button into the toolbar of a rich-text editor of a specific web page, code available here. This basic extension is based on the concept of the "content script" and works well because the toolbar is present as soon as the page has loaded.
Now, however, I'm confronted by another page where I cannot simply inject my button as soon as the page loads because the user needs to interact with the page first (make a selection or press a button) before the toolbar appears.
So I'm looking for a way to track any changes in the active tab (I have a URL pattern for the page). I don't want or need a browser action (i.e. the little button on the right-hand side of the omnibox), so I was hoping to get away with a background.js event page where I can declare an event listener for certain user-originated events but somehow it's not working.
To explain: I've got my manifest.json, great:
{
"name": "basic tab test",
"description": "blah di blah",
"version": "1.0",
"permissions": [
"activeTab"
],
"background": {
"scripts": ["background.js"], // background script shown below
"persistent": false
},
"content_scripts": [
{
"matches": [
"file://*" // for testing only, of course
],
"js": [
"contentscript.js" // <-- content script shown below
]
}
],
"manifest_version": 2
}
The background.js script looks like this at the moment:
console.log("in background.js");
chrome.tabs.getCurrent(function(tab) {
tab.onActivated.addListener(function(){
console.log("GOT HERE onActivated (inside tab)");
});
});
chrome.tabs.getCurrent(function(tab) {
tab.onZoomChange.addListener(function(){
console.log("GOT HERE onZoomChange (inside tab)");
});
});
// this is actually part of the message passing test
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
Of course, these are just tests, but none of the above events actually ever fire. Becoming slightly desperate, I then thought 'well, let's use the message passing method' to send messages from the contentscript.js to the background.js whenever the user presses a button. The contentscript.js looks like this:
document.addEventListener("DOMContentLoaded", function(event) {
console.log("just a canary - got here...");
var btn = document.getElementById("button");
if (btn) {
console.log("there is a button!");
} else {
console.log("there is NO button!");
}
btn.addEventListener("click", function () {
console.log("clicked the button!!!!");
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
})
});
Also, we never arrive inside this event handler (but why oh why?! this is standard jquery-less code for when the DOM is completely loaded). So, this is when I thought I might ask the assembled experts for advice.
TL;DR: I want to track events on the activeTab and if a given DOM element makes its appearance manipulate it (by injecting an element).
By default, "run_at" property for Content Script is "document_idle", which means you scripts will be injected after window.onload event fires, and obviously later than DOMContentLoaded event. So in fact your code in content script is not executed at all.
To make your code work, either:
Remove the outer DOMContentLoaded event listener
Or add "run_at": "document_start" part in your manifest.json
You could take a look at run_at part fore more details.
Related
I'm building a chrome extension which needs to redirect a script of a certain page. My background.js includes:
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
if (/js\example.js/.test(details.url))
// setTimeout(requestScript(details), 0);
return {
redirectUrl: chrome.extension.getURL("novoScript.js")
}
},
{urls: ['*://*.example.com/*.js']},
["blocking"]
);
The manifest.json includes:
"background": {
"scripts": ["background.js"],
"persistent": true
},
It works as expected, but the function only runs when I reload the page after having clicked the popup button. The first time I open the page in a new tab, it doesn't run. If I am in the page, and have clicked the popup button, it always works. If I haven't clicked, it doesn't matter how many times I reload, the redirect doesn't work.
I've tried erasing the whole content of popup.js, and it doesn't make a difference, so it's not because of any code there.
Also, I've checkedthe background.js file is not being ran again, so it seems that the listener is there, but it doesn't listen if I don't click the popup button. I've also added console.log to the listener function, and before I click the button it only logs calls to 'aobut:blank' url.
I'd like to allow the listener to work without clicking the popup, to avoid inconsistencies. Any help is appreciated.
I'm not sure about what was causing the problem. But an alternative approach that seems to be better overall, was pointed by #wOxxOm: declarativeNetRequest. With it, I applied a general rule for whenever the desired resource is requested.
Implementation:
manifest.json:
{
...
"declarative_net_request" : {
"rule_resources" : [{
"id": "ruleset_1",
"enabled": true,
"path": "redirectRules.json"
}]
},
"permissions": [
"declarativeNetRequest",
"*://*.example.com/*"
],
...
}
redirectRules.json:
[{
"id": 1,
"priority": 1,
"action": {"type": "redirect", "redirect": {"extensionPath": "/novoScript.js" }},
"condition" : {
"urlFilter" : "js/app.*.js",
"domains": ["example.com"],
"resourceTypes" : ["script"]
}
}]
If I understand you correctly when you first open the page it is not triggering onBeforeRequest. When you trigger the page load another way then it triggers onBeforeRequest as expected.
You may be able to capture what you want using onBeforeNavigate instead or some combination of onBeforeNavigate and onBeforeRequest.
A certainly full-proof way to capture any tab changes would be to do something like this in your background script:
chrome.tabs.onUpdated.addListener(function
(tabId, changeInfo, tab) {
// read changeInfo data and do something with it (like read the url)
if (changeInfo.url && ..url-comparison-here) {
// do something here
}
}
);
I'm trying to build a somehow dummy Chrome extension. I want it to run only in specific pages, so I'm using a Page Action.
Let's say I want the page action to run on the Instagram website, then (accordingly the docs), I would need something like this on my manifest.json right?
{
"manifest_version": 2,
"name": "Some name",
"version": "0.0.3",
"description": "Some description",
"content_scripts": [
{
"matches": [
"https://www.instagram.com/*"
],
"js": ["content.js"]
}
],
"page_action": {
"default_icon": "icon.png"
},
"background": {
"scripts": ["background.js"]
}
}
while the content script runs only on instagram pages as one would expect, the browser extension is not clickable (gray look, and when I click most options are not clickable).
this makes impossible to act upon extension button click. In my background.js I have:
function click(tab) {
console.log('click from ' + tab);
}
chrome.pageAction.onClicked.addListener(click);
that never gets called.
So, what's wrong that makes impossible to act upon extension click on some pages?
Note: I saw this question/answer, but couldn't find the problem/solution How can I add a click for pageAction?
You have to call pageAction.show in order for your pageAction button to be enabled (clickable).
The pageAction documentation says (emphasis mine):
You make a page action appear and be grayed out using the pageAction.show and pageAction.hide methods, respectively. By default, a page action appears grayed out. When you show it, you specify the tab in which the icon should appear. The icon remains visible until the tab is closed or starts displaying a different URL (because the user clicks a link, for example).
With a manifest.json content_scripts entry
Because you already have a content script that runs on the page you desire to have this function on, probably the easiest way to do this is to have your content script send a message to your background script telling it to show the page-action button for that tab.
Your content script could look something like:
chrome.runtime.sendMessage({type: showPageAction});
Your background script could look something like:
chrome.runtime.onMessage(function(message, sender, sendResponse) {
if(typeof message === 'object' && message.type === 'showPageAction') {
chrome.pageAction.show(sender.tab.id);
}
});
Without a manifest.json content_scripts entry
If you did not have a content script, you would probably want to use a webNavigation.onCompleted listener, or tabs.onUpdated listener, to listen for a change in the tab's URL in order to determine that the page-action button should be shown. Obviously, the trigger for calling pageAction.show() does not have to be the URL which is currently displayed in the tab, but that is the most common.
I've made a chrome extension that downloads some stuff from a certain site. Basically, it goes around through all links I'm interested in, stores them in an array and then downloads it one by one. The thing is, the storing is done in a separate file called download.js. Then, I proceed to send a message to popup.js using chrome.extension.sendRequest. I pick it up in popup.js with chrome.extension.onRequest.addListener. It works perfectly when I don't switch my tab, but I'd like it to work while I'm browsing some other stuff in the meantime. I can see the code reaching the point to send the request to popup.js through a console log, but I can't see what's going on in popup.js because when I switch my tab the popup console immediately closes.
download.js:
// logic behind link gathering and storing that works
...
gatherLinks().then(function() {
// logs is defined, don't worry
chrome.extension.sendRequest(logs);
)};
popup.js:
document.addEventListener('DOMContentLoaded', function() {
var downloadButton = document.getElementById('download');
downloadButton.addEventListener('click', downloadStuff);
});
function downloadStuff() {
chrome.tabs.executeScript({
file: 'jquery-3.1.1.min.js'
});
chrome.tabs.executeScript({
file: 'download.js'
});
chrome.extension.onRequest.addListener(function(message_logs) {
message_logs.forEach(function(log) {
chrome.downloads.download({
url: log.link,
filename: log.filename
});
}
}
manifest.json:
{
...
"permissions": [
"tabs",
"activeTab",
"downloads"
],
"background": {
"scripts": ["download.js"]
}
}
When you switch away, the popup window closes.
It does not hide the popup, the popup is properly closed, as you would close a tab. Therefore, its code is no longer executing and there's nothing to listen for your messages.
This is a job for background (or better, event) pages. They exist, invisibly, independent of what you're doing with the browser. Therefore, such a page should be the one to receive commands when the popup may not exist.
Also,
BIG SCARY WARNING!
If your content script and your background script are the same, there is a 99% probability you're doing something wrong. Do not try to reuse code in both, unless it's some auxilliary library - main logic should never be the same in those very different contexts.
I'm trying to make my first Chrome Extension without any prior JS knowledge, and I have some trouble doing it.
What does the extension do?
It's a page action extension for generating a string and copying it to the clipboard. The string includes certain element attributes from the DOM.
Scope
It's only applicable on two pages (the domains below are examples):
https://xxx.abc.com/CFM/Messages/CFMEWFA/*
https://xxx.abc.com/CFM/Messages/FraudPrevention/*
Elements of the extension
The extension has a popup.html with three clickable options to be chosen at the user's discretion:
No response
Invalid
Valid
The string is formatted based on the user's choice from the popup, and whether the tab URL contains "CFMEWFA" or "FraudPrevention".
popup.html
<!doctype html>
<html>
<body>
<script src="popup.js"></script>
<ul id="MENU">
<li id="MENUnoResponse">No reponse
</li>
<li id="MENUinValid">Invalid
</li>
<li id="MENUvalid">Valid
</li>
</ul>
</body>
</html>
popup.js is supposed to listen for clicks in popup.html, employ a multi item clickhandler, then message background.js at the event of a click. The message should include an argument corresponding to the li id in popup.html.
popup.js
var theParentMenu = document.querySelector("#MENU");
theParentMenu.addEventListener("click", userHasClicked, false);
function userHasClicked(e) {
if (e.target !== e.currentTarget) {
var clickedItem = e.target.id;
chrome.runtime.sendMessage({
directive: e.target.id
}, function(response) {
this.close();
});
};
e.stopPropagation();
}
background.js is governing where the extension icon is shown. It also listens for messages from popup.js (containing an argument determined by the user's choice from popup.html) before executing content.js, a script which runs in the tab.url fetching attributes from the DOM and generating the string. I have yet to start building content.js because of unresolved issues earlier in other files.
background.js
//Displays the page action extension only on specific pages
function checkForValidUrl(tabId, changeInfo, tab) {
if (tab.url.indexOf("https://xxx.abc.com/CFM/Messages/FraudPrevention/") == 0)
{
chrome.pageAction.show(tabId);
}
else if (tab.url.indexOf("https://xxx.abc.com/CFM/Messages/CFMEWFA/") == 0)
{
chrome.pageAction.show(tabId);
}
};
chrome.tabs.onUpdated.addListener(checkForValidUrl)
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
switch (request.directive) {
case "MENUnoReponse":
// execute the content script
chrome.tabs.executeScript(null, { // defaults to the current tab
//file: "contentscript.js", // script to inject into page and run in sandbox
//allFrames: true // This injects script into iframes in the page.
});
sendResponse({}); // sending back empty response to sender
case "MENUinValid":
// execute the content script
chrome.tabs.executeScript(null, { // defaults to the current tab
//file: "contentscript.js", // script to inject into page and run in sandbox
//allFrames: true // This injects script into iframes in the page.
});
sendResponse({}); // sending back empty response to sender
case "MENUvalid":
// execute the content script
chrome.tabs.executeScript(null, { // defaults to the current tab
//file: "contentscript.js", // script to inject into page and run in sandbox
//allFrames: true // This injects script into iframes in the page.
});
sendResponse({}); // sending back empty response to sender
break;
default:
// helps debug when request directive doesn't match
alert("Unmatched request of '" + request + "' from script to background.js from " + sender);
}
}
);
manifest.json
{
"manifest_version": 2,
"name": "EW logger",
"description": "This extension creates logs for early warning and fraud prevention cases",
"version": "1.0",
"page_action": {
"default_title": "EW",
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"tabs",
"clipboardWrite",
"https://xxx.abc.com/*"
]
}
What works:
The extension icon appears like it should.
My problems:
The options in popup.html are not working. Popup.js doesn't do anything when I click.
Do you have any suggestion to how I can "listen" for clicks in popup.html properly, and then send a message containing an argument to background.js?
Your script is running before the body is loaded, so the element is not found. You can fix this by moving the script tag to the bottom of the body. Alternatively, use <script src="popup.js" defer></script> to delay execution until the dom is loaded.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer
Also, you should use console.log(message) and the Chrome Devtools console to debug and check for errors.
https://developer.mozilla.org/en-US/docs/Web/API/Console/log
https://developers.google.com/web/tools/chrome-devtools/
I have created Chrome extension which should change page body color. It is working when I am clicking on the extension but I want it be done when the page loads, where an alert shows that controls is passing through code, it is not calling the function. Please help to fix this.
----------manifest.json-----------
{
"name": "My Page changer",
"description": "Make the current page red",
"version": "2.0",
"permissions": [
"activeTab"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_title": "Make this page blue"
},
"manifest_version": 2
}
------------------ background.js--------------------
debugger;
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
debugger;
alert('I am here too ');
/*chrome.tabs.executeScript({
code: 'document.body.style.backgroundColor="blue"'
//code : 'doWhatYouWant()'
});*/
// Execute some script when the page is fully (DOM) ready
chrome.tabs.executeScript(null, {code:"doWhatYouWant();"});
}
});
function doWhatYouWant(){
alert('I am inside doWhatYouWant');
document.body.style.backgroundColor="blue";
}
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
// No tabs or host permissions needed!
alert('i am here');
console.log('Turning ' + tab.url + ' red!');
chrome.tabs.executeScript({
code: 'document.body.style.backgroundColor="red"'
});
});
Your doWhatYouWant function lives in your background page, so you won't be able to call it from a content script.
If the code you want to run is more than a couple lines long, consider putting it into a file in your extension and using the file: field in the InjectDetails parameter when you invoke chrome.tabs.executeScript.
Also, if you want it to run on every page, you can declare it as a content script in your manifest, instead of having the chrome.tabs.onUpdated listener.
There is the "prince" example on google content script tutorial:
https://developer.chrome.com/extensions/content_scripts.html#pi
I tried when learning to "google-extenioning"(?) and it works fine.
Good Luck!
eidt - uh, forgot, files are here