Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  21] [ 5]  / answers: 1 / hits: 5916  / 10 Years ago, tue, december 16, 2014, 12:00:00

I'm trying to create my first Chrome extension right now. It's a simple pop-up window with a number of pictures of sloths in it. What I'm trying to do is make it so that when you click on the picture of the sloth it appends the image URL into the current text field in the content page.



Here is my JSON:



{
manifest_version: 2,

name : Instant Sloth,
description: One button, many sloth.,
version: 1,

permissions: [
https://secure.flickr.com/
],

browser_action: {
default_icon: icon.png,
default_popup: popup.html
},
content_scripts: [{
js: [jquery.min.js, tab.js, jquery-ui.min.js, input.js],
matches: [http://*/*, https://*/*],
run_at: document_end
}]
}


Where popup.html is the HTML file with the pictures of the sloths, and input.js is the script that I'm hoping will add interactivity, like here:



$(img).click(function(){
var form = $(document.activeElement);
var sloth = $(this).attr('src');
form.value = (form.value + + sloth);
});


I'm having trouble trying to figure out how to access elements of both the content page and the pop-up within the same script. I also have the input.js file linked to pop-up.html. Thanks for the help!


More From » jquery

 Answers
2

This page may answer a lot of questions: Architecture Overview



In short, you can't do that in one script, because the popup and the current open page are different contexts. You need a script in the popup that handles the click and gets the source URL, a script in the page (a Content Script) that inserts the text, and some form of communication between two.



One approach is to use Messaging, where you have the content script listening for a command from the popup. This approach is valid, but has a slight problem I described here: there is no 100% warranty that the content script is actually ready in a given tab.



In your case, it's much easier to just construct a short code snippet and inject it into the page programmatically.



// Popup code
$(document).ready(function() {
$(img).click(function() {
var sloth = $(this).attr('src');
var script = 'var form = document.activeElement;' +
+ 'form.value = (form.value + ' + sloth + ');';
chrome.tabs.executeScript({code : script});
});
});


P.S. You will need the activeTab permission in your manifest for this to work.


[#40585] Tuesday, December 16, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ellisw

Total Points: 625
Total Questions: 92
Total Answers: 88

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
ellisw questions
Mon, Aug 23, 21, 00:00, 3 Years ago
Fri, Nov 20, 20, 00:00, 4 Years ago
Sat, Jun 20, 20, 00:00, 4 Years ago
Tue, Apr 21, 20, 00:00, 4 Years ago
;