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
Related
I sucessfully inject a content script to a site for the first time. If I filled out some input fields the site hard reloads (to show some additional informations) and kills also my content script.
In my Chrome Extension I have a workaround for this:
browser.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
const tabURL = 'my-site.com';
if (tab.url.includes(tabURL) && changeInfo.title && changeInfo.title.includes(tabURL)) {
browser.tabs.executeScript(tabId, {
code: `
window.addEventListener("DOMContentLoaded", () => {
new MyApp();
});`
});
}
});
The problem is, it does not work in Firefox as a Firefox extension.
I use the Firefox webextension-polyfill
Is there another "workaround" which works for Firefox?
OR
How can I detect if a page / tab reloads in firefox (e.g. from background script)? (And also reload my content script again)
It could be the answer, because it works :)
// CHROME Version
if (tab.url.includes(tabURL) && changeInfo.title && changeInfo.title.includes(tabURL)
// FIREFOX VERSION
|| tab.url.includes(tabURL) && changeInfo.status === 'complete')
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.
background
I simply want to create a chrome extension where I click on the extension icon, it loads a popup that loads a javascript file.
I was able to do an html only popup simply by adding these two files:
manifest.json
{
..
"browser_action": {
"default_popup": "popup.html",
..
}
}
popup.html
<html>
..
hello world
</html>
problem
I want to actually load a chrome events page so that the popup page calls the events page and interacts with it.
what i have tried
I added this to manifest.json
"background": {
"scripts": ["eventsPage.js"],
"persistent": false
}
and added a simple eventsPage.js file:
chrome.runtime.onInstalled.addListener(onInit);
chrome.runtime.onStartup.addListener(onStartup);
function onInit() {
console.log("on init");
}
function onStartup() {
console.log("on startup");
}
if (chrome.runtime && chrome.runtime.onStartup) {
chrome.runtime.onStartup.addListener(function() {
console.log('on startup stuff');
});
}
when I launch the extension and click on inspect to see chrome dev tools.. nothing shows up on the console:
I've also tried adding the src of eventsPage.js to popup.html:
</head>
..
<script src="eventsPage.js"></script>
<body>
..
but that changes nothing, I can't even find the eventsPage.js source in chrome dev tools.
How do I do this?
Many ways:
Add a script for example popup.js in popup.html and call chrome.runtime.getBackgroundPage(function callback) to interact with event page.
popup.html
...
<script src="popup.js"></script>
...
popup.js
chrome.runtime.getBackgroundPage(backgroundPage => backgroundPage.testMethod());
eventsPage.js
const testMethod = () => console.log('test');
Use Message Passing(there are many examples in this link) to communicate with event page.
Since you want to transfer data between popup page and event page, there are many other workarounds, for example, we could use global storage such as chrome.storage to save/load/react to changes.
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'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: