I've inherited a chrome extension that once you visit a page it spins through the DOM and adds a span which contains a list of 4 links when you mouse over the span the list displays the 4 links (anchors). I'd like when you click one of these 4 links if it could show a jQuery-ui dialog box with a button. The text of this box will be dynamic but I just need to get the dialog box showing on link click for now.
I'm not seeing any errors in my console but I'm also not seeing the dialog present itself. I do see the console.log being spit out from line 8 of main.js with the ruleDialog DIV showing.
Prior to me making adjustments these links worked normally (performed an API call) and they worked fine so I know the extension as a whole is functional (besides my dialog not showing).
I've done some looking around here on SO and I've found a few questions slightly related to my problem but have not had success with getting my particular case to work.
Here is a screenshot showing what it adds to the page:
manifest.json:
{
"manifest_version": 2,
"name": "My Extension",
"short_name": "ME",
"author": "caleywoods",
"description": "my extension",
"version": "0.0.11",
"content_scripts": [
{
"matches": [
//my pages
],
"js": [
"jquery-2.1.4.min.js",
"jquery-ui.min.js",
"main.js"
],
"css": [
"style.css",
"jquery-ui.min.css"
]
}
],
"web_accessible_resources": [
"images/*"
],
"options_ui": {
"page": "options.html",
"chrome_style": true
},
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"storage",
//my pages (same as "matches")
]
}
main.js:
function addOurSpan() {
var diaDiv = document.createElement('DIV');
diaDiv.id = "ruleDialog";
diaDiv.innerHTML = "Testing!";
diaDiv.style = "display: none;">
console.log(diaDiv);
$('.link .flat-list.buttons').each(function(i, e) {
// Skip elements we've already added the dropdown to
if ($(e).has('.my-class').length) { return; }
// Create selected option/trigger div
var selected = document.createElement('DIV');
selected.className = 'dropdown lightdrop my-class';
var selectedSpan = document.createElement('SPAN');
selectedSpan.className = "selected";
$(selectedSpan).text("OUR ADDED BUTTON");
selected.appendChild(selectedSpan);
// Create options div
var options = document.createElement('DIV');
options.className = 'drop-choices';
// The rule by button label and hover-text
var rules = {
'Rule 1': 'Unrelated Stuff',
'Rule 2': 'Miscellaneous Stuff',
'Rule 3': 'Repetitive Stuff',
'Rule 4': 'Scam Stuff',
};
for (var r in rules) {
var ruleLink = document.createElement('A');
$(ruleLink).text(r);
ruleLink.title = rules[r];
ruleLink.className = 'choice';
$(ruleLink).click(function(ev) {
ev.preventDefault();
// $("#ruleDialog").dialog({
// modal:true,
// buttons: {
// Accept: function() {
// $( this ).dialog( "close" );
// }
// }
// });
$("#ruleDialog").dialog();
});
}
var li = document.createElement('LI');
var spacer = document.createElement('DIV');
spacer.className = "spacer";
spacer.appendChild(selected);
spacer.appendChild(options);
li.appendChild(spacer);
e.appendChild(li);
});
}
$(document).ready(function() { addOurSpan(); });
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;
}
});
I've struggle with this issue for a few hours and still don't know what I am missing.
I create player to play some videos. Extension added "Next" button, you click and it plays another video.
The list of which video it should play is host as symlink from local host - watch.ber.in.com/videos/list.js:
info_list = [
{"video":"first_video", "link":"https://watch.ber.in.com/player.html?channel=first_video", "info":"movie_tittle"},
"video":"second_video", "link":"https://watch.ber.in.com/player.html?channel=first_video", "info":"movie_tittle2"}
]
current_channel_index = info_list.findIndex(x => x.channel == player.channel)
document.getElementById('info-label').innerHTML = info_list[current_channel_index].info
document.getElementById('next-button').addEventListener('click',function () {window.location = info_list[current_channel_index+1].link})
document.getElementById('progress-label').innerHTML=current_channel_index+1 + '/2'
I have done some research how to update script from manifest v2 to manifest v3 and finally Chrome stopped showing errors, but also my "Next" button has stopped working and I can't really figure it out why.
This is my manifest.json file:
{
"manifest_version": 3,
"name": "video player",
"description": "lets watch some movies!",
"version": "2.2",
"permissions": [
"scripting",
"activeTab",
"contentSettings"
],
"content_scripts": [
{
"matches": [
"https://watch.ber.in.com/player.html*"
],
"run_at": "document_idle",
"js": [
"myscript.js"
]
}
],
"host_permissions":["<all_urls>"],
"web_accessible_resources": [
{
"matches": ["*://*/*", "http://*/*", "https://*/*"],
"resources": ["list.js"]
}
],
"content_security_policy": {
"extension_pages": "default-src 'self'"
}
}
and my myscript.js:
//Load verification list from server
var script=document.createElement("script");
script.src="https://watch.ber.in.com/videos/list.js";
document.body.appendChild(script);
//Create a progress label
var progress=document.createElement("label");
player_form = document.getElementById("player-form")
progress.id = "progress-label"
player_form.appendChild(progress);
//Change the label of change channel button
document.getElementsByTagName("input")[2].value="Change"
//Add info
var label=document.createElement("label");
player_status = document.getElementById("player-status")
label.id = "info-label"
player_status.appendChild(label);
//Move verification to the top of the page.
problemator = document.getElementById("problemator")
player_status.appendChild(problemator);
//Create next button
var button=document.createElement("button");
button.innerHTML= "Next";
button.className="button"
button.id="next-button"
problemator.appendChild(button);
//Change default status to "OK"
document.getElementsByTagName("select").status.value=200
Any idea what am I missing?
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);
}
);
});
This question already has an answer here:
Chrome Extension Context Menu: how to append div to page after clicking menu item
(1 answer)
Closed 5 years ago.
I am writing a simple Chrome Extension which enables disabled drop-down menus.
If I ran this same script in the Console, it works perfectly. However, through the extension it calls the functions but doesn't do anything.
Thank you in advance for your help.
manifest.json
{
"name": "4x6 Mac Menu",
"manifest_version": 2
"version": "0.1.4",
"description": "Overrides Disabled Drop Down",
"permissions": ["contextMenus"],
"background": {
"scripts": ["sample-click.js"]
}
}
sample-click.js
function Enable46(info, tab) {
console.log("Enable 4x6 was clicked.");
var inputs = document.getElementsByClassName('psSelect');
for(var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
console.log("Drop Enabled.");
}
chrome.contextMenus.create({
title: "Enable 4x6",
contexts: ["page"],
onclick: Enable46,
});
I also tried another approach to have a listener as background and while I get the console log, the event doesn't actually carry out the function
manifest.json
{
"name": "4x6 Enable",
"description": "Enable 4x6 Print Option on Mac",
"version": "0.1",
"manifest_version": 2,
"permissions": [
"contextMenus",
"activeTab"
],
"background": {
"persistent": false,
"scripts": ["bg.js"]
}
}
bg.js
/* Create a context-menu */
chrome.contextMenus.create({
id: "myContextMenu", // <-- mandatory with event-pages
title: "4x6 Label",
contexts: ["all"]
});
/* Register a listener for the `onClicked` event */
chrome.contextMenus.onClicked.addListener(function(info, tab) {
if (tab) {
/* Create the code to be injected */
var code = [
'var input = document.getElementsByClassName("psSelect");',
'for(var i = 0; i < inputs.length; i++) { inputs[i].disabled = false; }'
].join("\n");
console.log("Enable 4x6 was clicked.");
/* Inject the code into the current tab */
chrome.tabs.executeScript(tab.id, { code: code });
}
});
This solution worked. For whatever reason, it had to be split up into 3 files.
manifest.json
{
"name": "Enable Dropdown",
"description": "Enable Dropdown Menu",
"version": "0.3",
"manifest_version": 2,
"permissions": [
"contextMenus",
"activeTab"
],
"background": {
"persistent": false,
"scripts": ["bg.js"]
}
}
bg.js
/* Create a context-menu */
chrome.contextMenus.create({
id: "myContextMenu", // <-- mandatory with event-pages
title: "Enable Dropdown",
contexts: ["all"]
});
/* Register a listener for the `onClicked` event */
chrome.contextMenus.onClicked.addListener(function(info, tab) {
if (tab) {
/* Inject the code into the current tab */
/* chrome.tabs.executeScript(tab.id, { code: code }); */
chrome.tabs.executeScript(tab.id, {file: "content_script.js"});
}
});
content_script.js
var inputs = document.getElementsByClassName('psSelect');
for(var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
document.getElementById("PrintLabelsPrinter").value = "1-1";
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' });
});
}