I'm tried to run script on ContextMenu Click event. I'm used example ContextMenu which have manifest:
{
"name": "Context Menus Sample (with Event Page)",
"description": "Shows some of the features of the Context Menus API using an event page",
"version": "0.7",
"permissions": ["contextMenus"],
"background": {
"persistent": false,
"scripts": ["sample.js"]
},
"manifest_version": 2
}
sample.js:
function onClickHandler(info, tab) {
chrome.tabs.executeScript(null,
{code:"document.body.style.backgroundColor='" + e.target.id + "'"});
};
chrome.contextMenus.onClicked.addListener(onClickHandler);
chrome.runtime.onInstalled.addListener(function() {
var contexts = ["page","selection","link","editable","image","video",
"audio"];
for (var i = 0; i < contexts.length; i++) {
var context = contexts[i];
var title = "Test '" + context + "' menu item";
var id = chrome.contextMenus.create({"title": title, "contexts":[context],
"id": "context" + context});
}
chrome.contextMenus.create({"title": "Oops", "id": "child1"}, function() {
if (chrome.extension.lastError) {
console.log("Got expected error: " + chrome.extension.lastError.message);
}
});
});
and i also change onclick handler to:
function onClickHandler(info, tab) {
chrome.tabs.executeScript(null, {file: "content.js"});
};
when content.js is:
document.body.innerHTML = document.body.innerHTML.replace(new RegExp("text", "gi"), "replaced");
but both of that doesn't working. How to solve it?
Because this question has hundreds of views so I will answer this my old question to help anyone who has the same problem. The answer is based on wOxxOm's comment. I just need to add activeTab permission to the manifest. So should be like this:
{
"name": "Context Menus Sample (with Event Page)",
"description": "Shows some of the features of the Context Menus API using an event page",
"version": "0.7",
"permissions": ["contextMenus","activeTab"],
"background": {
"persistent": false,
"scripts": ["sample.js"]
},
"manifest_version": 2
}
My script before doesn't work because I have code that needs to read/change current active tab content. activeTab permission gives an extension temporary access to the currently active tab when the user invokes the extension - for example by clicking its browser action.
Related
Basically what I am trying to do is send a message from the popup.js by grabbing values from the input fields, and onMessage in the content_script to assign those values from that local scope to the global scope. I can't manage to do it! I can close the whole code in the onMessage function, but then to get to next function of the code I have to keep clicking save on the chrome extension. If someone knows this way better than I do with chrome extensions and what not please review my code and guide me to progress. I have been on this for like a week and my head is about to expload!
I have tried enclosing all the code in the onMessage function in the content_script. I have tried flipping which .js files are sending the message and trying to send the input fields from the extension as a response. I have tried to exclude the sendMessage out of the .click DOM function. Reviewed Messaging API on Google Chrome Extension and im puzzled.
content.js file
chrome.runtime.onMessage.addListener (
function(request) {
item_name = request.name;
item_color = request.color;
item_category = request.category;
item_size = request.size;
console.log(item_name);
console.log(item_color);
console.log(item_category);
console.log(item_size);
});
var url = window.location.href;
var i;
var item_category;
var item_name;
var item_color;
var item_size;
console.log(item_name);
console.log(item_color);
console.log(item_category);
console.log(item_size);
popup.js file
document.getElementById("save_input").onclick = function() {
var item_name_save = document.getElementById("item_name_save").value;
var item_color_save = document.getElementById("item_color_save").value;
var item_category_save = document.getElementById("item_category_save").value;
var item_size_save = document.getElementById("item_size_save").value;
chrome.storage.sync.set({'item_name_save' : item_name_save}, function() {
console.log('Value is set to ' + item_name_save);
});
chrome.storage.sync.set({'item_color_save' : item_color_save}, function() {
console.log('Value is set to ' + item_color_save);
});
chrome.storage.sync.set({'item_category_save' : item_category_save}, function() {
console.log('Value is set to ' + item_category_save);
});
chrome.storage.sync.set({'item_size_save' : item_size_save}, function() {
console.log('Value is set to ' + item_size_save);
});
const msg = { name: item_name_save,
color: item_color_save,
category: item_category_save,
size: item_size_save
};
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, msg, function() {
});
});
location.reload();
// window.close();
}
manifest.json
{
"manifest_version": 2,
"name": "Supreme bot",
"description": "A bot for Supreme",
"version": "1.0",
"background": {
"scripts": ["background.js"]
},
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html",
"default_title": "Supreme bot"
},
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["bot-functionallity.js"]
}
],
"permissions": [
"activeTab",
"tabs",
"storage",
"tabs"
]
}
(When all code is in the onMessage function, works but not as intended)
The Incorrect Functionality
I basically want the content.js to NOT be all inside of the onMessage function because that doesn't work properly, and have it assign values in the global scope from the onMessage function. I just want that info to be sent 1 time from the popup.js to the content.js.
I just set the value with chrome.storage.sync.set and use chrome.storage.sync.get in the other file...
I'm trying to create a click-to-dial firefox extension like in which an item is shown in the context menu when selecting a phone number( lets say it's 123456). When clicking on this item a localhost URL "http://localhost:49324/Home/Index?tel=123456" should be called (This URL is always listening).
So what i don't know is :
how to call a localhost URL in my js script
how to pass the phone number to my js and then to my localhost URL
How to add contexte menu item
i've tried to follow This tutorial that explains how to add a context menu but it didn't work (i guess that it's because my manifest.json script)
My manifest.json script is :
{
"manifest_version": 2,
"name": "OBS_Extension",
"version": "1.0",
"background": {
"scripts": ["OBS_Extension.js"]
},
"page_action": {
"default_icon": "icons/dial.png",
},
"permissions": [
"activeTab",
"tabs"
]
}
My OBS_Extension.js script is :
var contextMenu = require("sdk/context-menu");
var menuItem = contextMenu.Item({
label: "Click-To-Dial",
context: contextMenu.SelectionContext(),
contentScript: 'self.on("click", function () {' +
' var text = window.getSelection().toString();' +
' self.postMessage(text);' +
'});',
onMessage: function (selectionText) {
console.log(selectionText);
}
});
Basically I am trying to create an Auto Visitor Extension for Chrome to open a website's URL after some specific time. When I open the popup everything works fine but when the popup is close nothing works. I am trying to find out a method to run that Auto Visitor Extension even when the popup is close I have read multiple questions regarding this phenomena on Stack Overflow but none of them clarifies what I am looking for.
Here is my manifest file:
manifest.json
{
"manifest_version": 2,
"name": "Auto Visitor",
"description": "This extension will visit multiple pages you saved in extension",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": [
"background.js"
],
"persistent": false
},
"permissions": [
"activeTab",
"storage",
"tabs",
"http://*/",
"https://*/"
]
}
The background file that i want to run even when popup is close :
background.js
// this will work only when you denie the background script in manifest
chrome.runtime.onInstalled.addListener(function(details) {
var initTime = 5;
chrome.storage.local.set({"avtime": initTime}, function() {});
});
reloadMainTab();
function reloadMainTab() {
chrome.storage.local.get('avurl', function (result) {
var urlsToLoad = result.avurl;
console.log(urlsToLoad);
if(urlsToLoad==undefined){
// do nothing
}else{
var urlsArr = urlsToLoad.split(",");
chrome.storage.local.get('avtime', function (result) {
var thisTime = result.avtime;
/*
setting it to -1 because it gets incremented by 1
when it goes into getSelected method
*/
var index=-1;
setInterval(function(){
if(index < urlsArr.length-1){
chrome.tabs.getSelected(function (tab) {
// console.log('index in get selected'+index)
chrome.tabs.update(tab.id,{url: urlsArr[index]});
});
index++;
}else{
index=-1;
}
}, thisTime+"000");
});
}
});
}
any help would be really appreciated
Looking to squeeze in the CSS for Bootstrap's Popover somewhere in my Chrome Extension. That's literally all I need to do. Include the CSS for a library so my popover (tooltip) is styled.
So far I've tried InsertCSS() in the background page, and adding a stylesheet element appended to the head which kept throwing an error requiring it to be listed on "web_accessible_resources" which it was. Spelling was all correct too.
My code:
NOTE The content_script file is included for posterity. I don't think it's valuable here, but ymmv. Way too long, but It's there. Yes there is a frame on the page I'm editing.
Manifest.json
{
"name": "RMP",
"description": "Work in Progress",
"manifest_version": 2,
"version": "0.8",
"icons": {
"16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png"
},
"permissions": [
"activeTab",
"http://*/",
"https://*/"
],
"background": {
"scripts": ["jquery-3.2.1.min.js","bootstrap.min.js","background.js"],
"persistent": false
},
"browser_action": {
"default_title": "Click me!"
}
}
background.js which included a commented out attempt.
// On Extension Icon click, inject script
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id, {file: "jquery-3.2.1.min.js"}, function () {
chrome.tabs.executeScript(tab.id, {file: "bootstrap.min.js"}, function() {
//chrome.tabs.insertCSS(tab.id, {file: "bootstrap.min.css", allFrames: "true"});
chrome.tabs.executeScript(tab.id, {file: "content_script.js"});
});
});
});
And my Content_Script file (reduced code not needed for question. Can post on request or on old posts of mine.)
// Handle page's frame (to allow DOM access)
var page = top.frames["TargetContent"].document;
**STUFF HAPPENS HERE.................**
function addPopover(profPage,profElement) {
// Retrieve & Format Professor Data
var name = profElement.textContent;
var quality = profPage.getElementsByClassName('grade')[0].textContent;
var difficulty = profPage.getElementsByClassName('grade')[2].textContent;
var ratings = profPage.getElementsByClassName('table-toggle rating-count active')[0].textContent;
ratings = ratings.trim();
// Concatenate into 1 string
var content = "Overall Quality: " + quality + "<br />" + "Difficulty: " + difficulty + "<br />" + ratings;
// Set attributes for popover
profElement.setAttribute("data-toggle","popover");
profElement.setAttribute("data-trigger","hover");
profElement.setAttribute("title",name);
profElement.setAttribute("data-content",content);
profElement.setAttribute("data-html",true);
$(profElement).popover();
}
I am writing my First Chrome Plugin and I just want to get some text present on the current webpage and show it as a alert when i click the Extension. Lets say I am using any any webpage on www.google.com after some Search query, Google shows something like "About 1,21,00,00,000 results (0.39 seconds) " . I want to show this Text as an alert when i execute my plugin. This is what i am doing.
here is the manifest.json that i am using
{
"manifest_version": 2,
"name": "Getting started example",
"description": "This extension shows a Google Image search result for the current page",
"version": "1.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["*://*.google.com/*"],
"js": ["content.js"]
}],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
]
}
Here is my popup.js
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("checkPage").addEventListener("click", handler);
});`
function handler() {
var a = document.getElementById("resultStats");
alert(a.innerText); // or alert(a.innerHTML);
}
Here is my 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);
}
});
Here is my background.js
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?google\.com/;
// A function to use as callback
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);
}
});
1) run content scrip after document ready ** check "run_at"
"content_scripts": [{
"run_at": "document_idle",
"matches"["*://*.google.com/*"],
"js": ["content.js"]
}],
2) on click of extension make another js to run( popup js). The popup js has access to the ( open page document)
// A function to use as callback
function doStuffWithDom() {
//console.log('I received the following DOM content:\n' + domContent);
//get tabID when browser action clicked # tabId = tab.id
chrome.tabs.executeScript(tabId, {file: "js/popup.js"});
}
3) In popup JS simple you can set alert
var a = document.getElementById("resultStats");
alert(a.innerText); // or alert(a.innerHTML);
Just remove "default_popup" part in manifest.json, as you have listened to chrome.browserAction.onClicked event in background page. They can't live at the same time.