I'm developing an extension for Google Chrome. I have created an icon for my extension. What I'd like to do, is the following:
A user clicks extension's icon.
A new tab is opened.
Content scripts are run as set in manifest file, but only in this
tab.
I think it's clear, but e.g.: let's say I set in my manifest file a following property:
"content_scripts" : [
{
"matches" : ["http://stackoverflow.com"],
"js" : ["script.js"]
}
]
And let's say I have 2 tabs: the first one was opened manually, and the second one was opened by clicking extension's icon. Now, I open the stackoverflow's index page in both tabs. In the first tab nothing happens, but in the second one the "script.js" script is run.
How can I achieve it? I know I can implement a tab's id checking, but isn't there any simpler way to achieve it?
You shouldn't use the content_scripts entry in the manifest in this case. You can use chrome.tabs.executeScript calls to run the content scripts. You will need to track which tabs you created but that's not hard.
You can have something like this in a background script:
var createdTabs = {};
chrome.browserAction.onClicked.addListener(function() {
chrome.tabs.create( {}, function( tab ) {
createdTabs[tab.id] = true;
}
}
chrome.tabs.onUpdate.addListener(function(tabId, changeInfo) {
if( createdTabs[tabId] && changeInfo.url )
chrome.tabs.executeScript( tabId, {file: 'script.js'} );
}
Related
I would like to ask a way to inject css or delete injected css through browse action pop up window for the chrome extension. I had try to look through few places to get ideal on how to do it but I fail to understand them.
I would like to make extension which similar to "A browser action with a popup that changes the page color" but click on the div in the popup.html to load or unload the css file that created.
This is my current work (https://github.com/Zhekoay/Self-Custom-Dark-Theme) which direct insert css using content script. Now i would like to make it able to load or unload differently instead one-time load all.
Chrome API can't remove CSS injected via manifest.json.
Inject the code just like the demo extension does, but use a file parameter with a name of your content script that will add or remove (if it exists) a link element under document.documentElement with an id equal to chrome.runtime.id and href pointing to a web accessible CSS file.
remove "content_scripts" from manifest.json
add "web_accessible_resources": ["*.css"] to manifest.json
add a click handler for the div in popup.js
in the click handler: chrome.tabs.executeScript({file: 'content.js'});
content.js:
(function() {
var styleElement = document.getElementById(chrome.runtime.id);
if (styleElement) {
styleElement.remove();
return;
}
var css = ({
'www.youtube.com': 'app_yt_HoveredImg.css',
'www.messenger.com': 'fb_messenger_styles.css',
'www.google.com': 'google_styles.css',
'translate.google.com': 'google_styles.css',
'apis.google.com': 'google_styles.css',
})[location.hostname];
if (!css) {
return;
}
styleElement = document.createElement('link');
styleElement.id = chrome.runtime.id;
styleElement.rel = 'stylesheet';
styleElement.href = chrome.runtime.getURL(css);
document.documentElement.appendChild(styleElement);
})();
Note, in this workflow you only need "permissions": ["activeTab"] instead of "tabs": the advantage is that activeTab doesn't ask for permissions when the extension is installed.
I have a created a desktop notification using google extension which works great:
icon = '';
var popup = window.webkitNotifications.createNotification(my notification');
icon, 'Awesome title', 'Click here to view more. ');
popup.show();
Is there a way to launch the actual google extension popup.html (as shown on the image below), when the user click on the the desktop notification?
Thanks.
Short answer is that you can't, but if you want to open the popup in a new tab instead, this is how you would do it:
Put this before you call show
popup.onclick = function() {
chrome.tabs.create({url : "popup.html"});
popup.cancel();
}
I wanted to add to the comment that Miscreant posted.
One approach that might work would be to setup a keyboard shortcut for
the pop up in the extension's manifest, then use an executable file to
artificially trigger that keyboard shortcut. See Native Messaging for
more info about how to communicate with an executable file from an
extension
This is how you set up a shortcut key that opens your extension.
...
"commands": {
"_execute_browser_action": {
"suggested_key": {
"default": "Ctrl+Shift+Y"
}
}
Here's the API on 'commands'.
I want to ask is there ANY way or extension that can pre-highlight text within the iframe whenever a new window is opened containing iframe? I have tried many extension but none of them works.
I need to filter out content based on certain keywords and the content is within iframe. I can do it with CTRL+F but there are many keywords like 10-15 within each article to be found. So it makes my job very tough and time consuming. Few extensions that I have tried from chrome are multi highlighter, pearls, FF but none of them seems to work.
I also know the reason why these extension can't access content within the iframe i.e. due to cross origin policies.
But I also remember around an year ago I worked with chrome extension named 'Autofill' that could pre-select form elements whenever I opened new chrome window containing iframe.
So is there any work around?
You can set your extension permission to run content scripts in all frames as document at http://developer.chrome.com/extensions/content_scripts.html#registration by setting all_frames to true in the content scripts section of your manifest file. Adding to Google's example from that page, part of your manifest file might look like
{
"name": "My extension",
...
"content_scripts": [
{
"matches": ["http://www.google.com/*"],
"css": ["mystyles.css"],
"js": ["jquery.js", "myscript.js"],
"all_frames": true
}
],
...
}
You'll need to be careful since your content scripts are going to be inject into the page once for the parent page and one for each iFrame on the page. Once your content script is injected into all frames on the page you can work your magic with finding and highlighting text.
if (window === top) {
console.log('Running inside the main document', location.href);
} else {
console.log('Running inside the frame document', location.href,
[...document.querySelectorAll('*')]);
}
I'm brand new to making Chrome Extensions and have done the simple tutorials, but I'm having trouble finding what I need. I want the extension to allow a user to chose an image on a webpage, and then copy the URL for that image into the extension. Can anyone help me out? I'm sure if I see an example I'd get a better grasp on how extensions can interact with a page.
From what I understand of your question, I'd say you want to create a context menu item that shows up when you right-click an image. For example, in your background script, use:
chrome.contextMenus.create({
title: "Use URL of image somehow",
contexts:["image"],
onclick: function(info) {
handleImageURL(info.srcUrl);
}
});
function handleImageURL(url) {
// now do something with the URL string in the background page
}
This will add a context menu item that shows up on all pages, but only when you right-click on images. When the user selects it, the onclick handler of the menu item fires handleImageURL with the URL of the image as the argument. The URL can be processed in any way you like, e.g., saved in a localStorage list, sent to a server via Ajax, or passed in a message to a listening content script in the current tab.
EDIT with alternative:
You might want a content script that gets injected into every page. The script could bind an event listener to every image element at load time:
// in my_content_script.js...
var imgs = document.getElementsByTagName("img");
for(var i = 0, i < imgs.length; ++i) {
imgs[i].addEventListener("click", function() {
alert(this.src);
// do things with the image URL, this.src
});
}
To inject it into all subdomains of example.com, your manifest would include:
...
"content_scripts": {
"matches":["*://*.example.com/*"],
"scripts":["my_content_script.js"]
},
...
Note that this pure-JS solution doesn't attach listeners to images dynamically added after load time. To do that in your content script with jQuery, use:
$(document).on("click", " img", function() {
alert(this.src);
});
And add your jQuery file name to the scripts array in your manifest, next to my_content_script.js.
Based on this Google Chrome Extension sample:
var images = [].slice.apply(document.getElementsByTagName('img'));
var imageURLs = images.map(function(image) {
return image.src;
});
chrome.extension.sendRequest(images);
For a more detailed example (e.g. how to handle the request), you can check out this extension I wrote called Image Downloader
I have a question about writing Google Chrome Extension. My goal now is to detect that if a tab is created or a URL of a tab has been changed.
Practically, I want to insert a dictionary .js from a link online to any webpage on Chrome, and the script will run as background.html. For example, if you open the browser and go to your homepage, it will run the script to insert dictionary.js into that page. When a new tab is created or a new page is open, it will run the script too. And when people change tab's url, it will run the script too. How do I detect if the tab changes in such situations? Ok, here is my ... code, i guess, to explain that.
chrome.someFunctionThatDetectTheSituationsAbove(function() {
insertDictionaryScript();//I'd love to have the script of detection, not the insertDictionaryScript();
}
I would appreciate for any idea. Thank you. :P.
[x]
Just add this on your background.js :
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
insertDictionaryScript();
});
chrome.tabs.onCreated.addListener(function(tab) {
insertDictionaryScript();
});
There's also onActivated event:
chrome.tabs.onActivated.addListener(function(tabId, changeInfo, tab) {
insertDictionaryScript();
});
What you are describing is called a content script. You don't need any coding for that, just make a declaration in the manifest file. More about content scripts here.
You can detect new tab creation by adding a listener to the onCreated event.
You can detect the url change of the tab by adding a listener to the onUpdated event.
To detect the tab change in google chrome extensions:
In your background script.js add the below code:
chrome.tabs.onActivated.addListener(function() {
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
var currentURL = tabs[0].url;
console.log(currentURL);
})
});