How to add a script code in my html in real time on browser open it

感情迁移 提交于 2019-12-13 09:27:25

问题


I want add a script code function in my html page, i'm tried using $(element).append('my script') but, this method has add like a text, no like code.

How i can do this?

I executed this code in my page console:

document.querySelector("body").append('<script> function validarValorElemento(e){   var xpathWay = "xpath=//"+e.target.tagName+"[@class=\'" + e.target.className+"\']"    var elementValue = e.target.textContent  alert(xpathWay) alert(elementValue)}</script>');

This is the result.


回答1:


IF I understand your question correctly -- that is, if you want to inject code into an existing webpage where you don't have access to the source code -- then:

The simplest way to do this is with a browser extension called TamperMonkey - it allows you to inject javascript into any webpage, based on the URL.

TamperMonkey scripts are installed (or written) in each person's browser, individually, and they only effect the webpage on that one computer. So, if your friend also wants to see the same effect, he also needs to install the TamperMonkey extension and add your script - which is why there are now millions of TamperMonkey users around the world. Hugely amazing product - many thanks to Jan Biniok.

There are also tons of pre-existing Tampermonkey scripts at the GreasyFork script repository.

TamperMonkey comes out of a previous extension called GreaseMonkey, so anywhere you see variations of that name, it probably also relates to TamperMonkey. The documentation for TamperMonkey is here:

https://tampermonkey.net/documentation.php




回答2:


Why don't you just add it inside the HTML directly?

However, you can insert any tag with content into your HTML via JavaScript like this:

var htmlToInsert = '<div class="inserted">I am added dynamically</div>';

var target = document.querySelector('#container');
target.innerHTML += htmlToInsert;
#container {
 padding: 10px;
 background: #000;
 color: #fff;
}

.inserted {
  margin: 20px 0;
  width: 200px;
  height: 200px;
  background: #c00;
}
<div id="container">I've been here all the time</div>


来源:https://stackoverflow.com/questions/54405955/how-to-add-a-script-code-in-my-html-in-real-time-on-browser-open-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!