Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
164
rated 0 times [  169] [ 5]  / answers: 1 / hits: 20472  / 11 Years ago, tue, december 24, 2013, 12:00:00

I am trying to execute javascript on a page when I click on a button in popup.html. I tried to use such a way:



In background.js:



chrome.tabs.onUpdated.addListener(function(tabId, changeInfo){
if(changeInfo.status == loading) {
insert(tabId);
}
});
function insert(tabId) {
chrome.tabs.get(tabId, function(tab) {
$('button').click(function() {
chrome.tabs.executeScript(tab.id, {file: 'js/alert.js'});
});
});
}


Alert.js consists only of one string: alert('works');



Alert is just an example. Real script should do some DOM manipulation with opened tab after user clicks on a button im popup.html.


More From » jquery

 Answers
11

I wrote a demo for your need.



https://gist.github.com/greatghoul/8120275






alert.js



alert('hello ' + document.location.href);


background.js



// empty file, but needed


icon.png



icon



manifest.json



{
manifest_version: 2,

name: Click to execute,
description: Execute script after click in popup.html (chrome extension) http://stackoverflow.com/questions/20764517/execute-script-after-click-in-popup-html-chrome-extension.,
version: 1.0,

icons: {
48: icon.png
},

permissions: [
tabs, <all_urls>
],

browser_action: {
default_icon: icon.png,
default_popup: popup.html
},

background: {
scripts: [background.js],
persistent: false
}
}


popup.html



<!DOCTYPE html>
<html>
<body style=width: 300px>
Open <a href=http://stackoverflow.com target=_blank>this page</a> and then
<button id=clickme>click me</button>
<script type=text/javascript src=popup.js></script>
</body>
</html>


popup.js



// var app = chrome.runtime.getBackgroundPage();

function hello() {
chrome.tabs.executeScript({
file: 'alert.js'
});
}

document.getElementById('clickme').addEventListener('click', hello);

[#73561] Monday, December 23, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
joseluispauld

Total Points: 13
Total Questions: 132
Total Answers: 98

Location: Venezuela
Member since Sat, Apr 24, 2021
3 Years ago
;