Turning bookmarklet into Chrome extension - javascript

I'm trying to use loadURI() in a Google Chrome extension so that I can execute a bookmarklet when the toolbar button is pressed.
// in background.html
chrome.browserAction.onClicked.addListener(function(tab) {
console.log('clicked!');
chrome.tabs.executeScript(tab.id, {code: "loadURI('http://www.google.com')"});
});
All I get is 'clicked!' in the log and nothing else happens. No errors. Does anyone know what I'm doing wrong?

loadURI() is a Firefox specific function (docs).
The equivalent in Chrome is the chrome.tabs.update() function as documented here.
The correct code would be:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.update(tab.id, {url: "http://www.google.com"});
});
Remember to include the protocol eg. http: or javascript:

Related

Need to open a chrome extension from button click + HTML + JS

Need to open chrome extension from html button click.
I tried to use chrome.runtime to open an extension but there is no use.
The program executes but the extension is not opening.
<!DOCTYPE html>
<html>
<head>
<script> 
// This function will trigger the Chrome extension with the specified ID
function runChromeExtension(extensionId) {
console.log(extensionId)
// Check if the extension is already installed 
if (typeof (chrome) !== "undefined" && chrome.runtime) {
// If the extension is installed, send a message to it
chrome.runtime.sendMessage(extensionId, { action: "run" }, function (response) {
console.log(response);
});
} else {// If the extension is not installed, show an error message
console.error("Chrome extension not found");
}
}</script>
</head>
<body>
<button onclick="runChromeExtension('anflghppebdhjipndogapfagemgnlblh')">Run Chrome Extension</button>
</body>
</html>
Any suggestions or am doing anything wrong?
Kindly Note: Security settings can be modified to run the above program.
If you own chrome extension then
Add your website url in externally_connectable key in manifest.json
"externally_connectable": {
"matches": ["http://mywebsite.com/*"]
},
If your domain not exist in any installed extension then
chrome make chrome.runtime is undefined

Chrome Web Extension stops because of "Disable developer mode extensions" Chrome popup

I wrote a Web Extension which starts surfing specified websites automatically (to simulate/train user profiles by "collecting" website cookies) after the Chrome browser is opened.
I know that you can disable the popup by whitelisting it for your own Web Extension:
Disable developer mode extensions pop up in Chrome
But: My Web Extension has to run automatically on 8-16 virtual machines on Linux without a GUI and i don't know whether it is possible and how to do it.
My Extension opens the first URL as expected, but then the popup comes into play and stops further surfing. If i open another tab per hand it continues to work, but opening a tab via Javascript doesn't do the trick. My code usually doesn't have to handle multiple tabs, because everything is done with one tab. Maybe i'm executing the code at the wrong time. The code works perfectly, when the popup doesn't come.
My code without tab opening:
background.js
var shouldMessageBeSent = true;
chrome.windows.onCreated.addListener(function() {
chrome.tabs.update({url:"https://stackoverflow.com/"}); // placeholder URL
});
chrome.webNavigation.onCompleted.addListener(function() {
if (shouldMessageBeSent == true) {
chrome.tabs.query({"currentWindow": true}, function(tabs) {
shouldMessageBeSent = false;
chrome.tabs.sendMessage(tabs[0].id, {txt: "newURLvisited"}, function(response) {});
});
}
});
chrome.runtime.onMessage.addListener(gotMessage);
function gotMessage(message) {
if (Array.isArray(message)) { // It's an array in my code
linksToVisit = message;
}
visitLinks(linksToVisit); // visits all the given links (the links are filtered in my code)
}
Content.js (highly simplified)
chrome.runtime.onMessage.addListener(gotMessage);
function gotMessage(message) {
if (message.txt === "newURLvisited") {
var allLinks = document.getElementsByTagName("a");
chrome.runtime.sendMessage(allLinks);
}
}
Any ideas what to fix? It may have to do something with active window/tab focus.
Apparently you can install a policy for Chrome, provided as a template from Google, which you can edit to your taste before that; I suppose you can do a similar thing on Mac and Linux just in a JSON editor.

Chrome extension: Activate and execute background.js on click from popup.js

As I understand from Manage Events with Background Scripts and Migrate to Event Driven Background Scripts background script should be activated when events triggered.
background.js
chrome.runtime.onMessage.addListener((message, sender, reply) => {
const json = message.data;
// some code
reply({ result: true })
return true;
});
popup.js
chrome.runtime.sendMessage({ data: [<ArrayWithData>] },
function (response) {
logger.log(response);
}
);
Everything works well, but only in case of active background.
Why background not become active? Can someone explain what is my mistake?
Or how can I activate and execute background.js on click from popup.js?
I know that if I change persistence: true in manifest.json or just remove it, everything will works fine. But I want to keep persistence false and trigger background.js when needed.
You missed this part in the documentation that explains how a background script should be activated from popup.js. After retrieving the background page object, you just need to call any function or even access a field.
I always put this at the top of my popup.js:
// Initialize background page
chrome.runtime.getBackgroundPage(function(backgroundPage) {
console = backgroundPage.console;
})
That way I can also view console logs from the popup together with logs from the background view

Send message from popup to content script?

Suppose I want to run a content script when I click a button in the popup page in a google chrome extension?
I have tried the following:
//popup.js
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', clicked);
main();
});
function clicked(){
chrome.tabs.getCurrent(
function(tab){
console.log(tab);
chrome.tabs.sendMessage(tab.id, "doSomething");
}
);
}
And in the content script:
chrome.extension.onMessage.addListener(
function(message, sender, sendResponse){
console.log("hello world");
}
);
The problem is that the tab in the callback from chrome.tabs.getCurrent( ) is undefined.
Have you given permissions for tabs in manifest.json as shown here.
"permissions": [
"tabs"
],
Moreover tab.id which the following code returns is of popup view (NOT A CONTENT SCRIPT TAB.ID)
chrome.tabs.getCurrent(
function(tab){
console.log(tab);
chrome.tabs.sendMessage(tab.id, "doSomething");
}
);
If you want to send message to tab you are browsing use following code's tab.id, it gives correct results
chrome.tabs.query({"status":"complete","windowId":chrome.windows.WINDOW_ID_CURRENT,"active":true}, function(tabs){
console.log(JSON.stringify(tabs[0]));
console.log(tabs[0].id);
});
Let me know if you need more information
The answer provided by #Sudarshan is valid and works fine, but I just found another solution to my problem. Just thought i put it here:
function clicked() {
chrome.tabs.executeScript(null,
{code:"console.log('hello world');"});
}
It will inject and execute the script.

Google Chrome Extension Running in the background

I am trying to make a google extension that basically checks the current tab URL to see if the URL is our prefix, so far I have this in my background.html (I have tab and background permissions set in my manifest):
<script type="text/javascript">
chrome.tabs.getSelected(null, function(tab) {
alert(tab.url);
if(tab.url == "http://www.google.com") {
alert("YOU'RE AT GOOGLE");
}
//changeTabURL(tab.url, tab);
});
</script>
So this seems to run only when I first load the extension, it tells me "chrome://extensions" and then it disappears. How do I get it to check each time the user goes to a new URL? Is this possible?
Thanks!
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if(changeInfo.status == "loading"){
//do url check
}
});
use the following:
chrome.tabs.onUpdated.addListener(function(Tab tab) {...});
See the documentation here.

Categories