0

I am adding a popup Div with help of content script. I added a button to close that DIV and for that purpose I called onClick event for my function popClose() but it gives function undefined. How do I make it happen?

My Content Script code is given below:

var currentURL = document.location.href;
var body = document.getElementsByTagName("body")[0];
body.setAttribute("style", "background-color:red");

//get Top BlueBar Reference
var blueBar = document.getElementById("blueBar");
var blueBarHtml = blueBar.innerHTML;

//popUp Div for Options

var popUpDiv = "<div onclick='closepop();' class='popUpDiv'><div class=close>X</div></div>";
blueBar.innerHTML = popUpDiv+blueBarHtml;

//get page Nav ID
var tinyMan = chrome.extension.getURL("tinyman.png");
var pageNav = document.getElementById("pageNav");

var red = chrome.extension.getURL("red.png");
var yellow = chrome.extension.getURL("yellow.png");
var green = chrome.extension.getURL("green.png");
var blue = chrome.extension.getURL("blue.png");

var pageNavHtml = pageNav.innerHTML;
var liHTML = '<li id="Extra" class="navItem topNavLink middleLink">';
liHTML+='<a><img src="'+tinyMan+'" border="0" style="margin-bottom: 4px; display: inline-block;">';
liHTML+="<a>"
liHTML+='<div class="menuPulldown" style="display:block;"></div>'
liHTML+='</a>';  
liHTML+='</li>';
//set new HTML

pageNav.innerHTML = liHTML+pageNavHtml;

function closepop()
{
    alert("jj");
}
Volatil3
  • 14,253
  • 38
  • 134
  • 263
  • 1
    Have you tried defining the function before setting it as the callback? (ie, move your bottom lines above `var popUpDiv...`) – Scott Mermelstein Jul 29 '13 at 20:11
  • 2
    Possible duplicate: [Inject code in a page using a Content script](http://stackoverflow.com/q/9515704/710446). Also relevant: [Can a site invoke a browser extension?](http://stackoverflow.com/q/10526995/710446) – apsillers Jul 29 '13 at 20:31
  • @apsillers please make it as an Answer. I think having an external JS file is the best idea. – Volatil3 Jul 29 '13 at 20:42

1 Answers1

1

Well, I just added the content of my function in the head of DOM and then called it.

var head = document.getElementsByTagName("head")[0];
fn = "function closepop(){alert('jj');}";

var script = document.createElement('script');
script.setAttribute("type", "application/javascript");
script.textContent = fn;
head.appendChild(script);

Is there any cleaner way to do it?

Volatil3
  • 14,253
  • 38
  • 134
  • 263
  • 1
    In general, no; but in your particular case, yes. Content scripts share the DOM of the main page, so content scripts can "hear" main-page DOM events like `click`. Instead of an inline `onclick` listener, you can use [`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener) to bind `closepop` as a listener for the `click` event on your div: `document.querySelector(".popUpDiv").addEventListener("click", popup)` – apsillers Jul 29 '13 at 20:41