且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在用户点击按钮时执行javascript

更新时间:2023-12-01 22:37:04

如果您想使用位于另一个文件中的函数,则需要导入这些文件:

 <脚本类型=text / javascriptsrc =/ path / to / script.js>< / script> 

但是,在Google Chrome浏览器扩展程序中,如果您希望在执行脚本时点击按钮(从扩展页面),您可以使用 chrome.tabs.executeScript 功能

  //在当前选项卡上运行该脚本。第一个参数是标签ID。 
chrome.tabs.executeScript(null,{file:'/path/to/script.js'});

这一切都取决于你的场景,当你如上所示的executeScript时,它会注入一个内容脚本到该DOM中。如果您导入该脚本,您只需在当前DOM中使用这些功能(在这种情况下是扩展页面,而不是标签)。



希望这有帮助! p>

I am creating an extension for Chrome. I want to execute a script when the user clicks a button. Here is the code i currently have in my html file

<input type="button" id ="button" onclick='notEmpty()' value="Play"/>

The notEmpty() is in a javascript (.js) file. How can I execute another script in the notEmpty() function?

If you want to use functions that are located in another file, you would need to import those files:

<script type="text/javascript" src="/path/to/script.js"></script>

But, in Google Chrome Extensions, if you want to "execute" a script when you click on a button (from an extension page), you can use the chrome.tabs.executeScript functionality

// Run that script on the current tab. The first argument is the tab id.
chrome.tabs.executeScript(null, {file: '/path/to/script.js'});

It all depends on your scenario, when you "executeScript" as shown above, it will inject a content script into that DOM. If you import that script, you will just use those functionality in the current DOM (in that case the extension page, not the tab).

Hope that helped!