0

In the content script, I'm dynamically adding a button. And I want to execute a function that already exists in the page when a button is clicked. I tried to do:

<button onClick="test();">Test</button>

But when I click on it, I'm getting error test() is not defined. How can I execute this function?

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
user2452483
  • 357
  • 1
  • 4
  • 13
  • To clarify: you really mean it exists in the _page_ scripts and not your content script, correct? – Xan Jan 04 '19 at 10:24
  • Can you also add how you're creating the button? – Xan Jan 04 '19 at 10:24
  • 4
    Sounds like https://crbug.com/912069 which was broken in Chrome 71 and fixed in 72. You'll need to assign the click handler inside a [page-level script](https://stackoverflow.com/a/9517879). – wOxxOm Jan 04 '19 at 10:25
  • Please add all relevant code, because what you're trying to do should work fine: https://jsfiddle.net/khrismuc/kzx92gey/ –  Jan 04 '19 at 10:27
  • that should work fine if test() is defined properly. how did you define test() function? – ACD Jan 04 '19 at 10:30
  • Please note: `test()` was not defined by the OP, and jsfiddle cannot demonstrate this behavior. This is specific to interaction between pages and browser extension content scripts. – Xan Jan 04 '19 at 10:33
  • `test()` was already accessible from chrome console before the extension. And I'm adding a button to page as text to `innerHtml`. It renders correctly and I can see `onClick` from the console, but when I click on it I'm getting `test() is not defined` error. – user2452483 Jan 04 '19 at 10:39

1 Answers1

-3

As far as i understand your question, these lines would work for you

function oldFunc(){
    console.log("Hello");
}
var btn = document.createElement('button');
btn.onclick = oldFunc;
btn.innerHTML = "Dynamic Button";
document.body.appendChild(btn);
Salman Saleem
  • 439
  • 4
  • 14