Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to Insert "Script" element in the page? #3478

Answered by mdmintz
blevoh asked this question in Q&A
Discussion options

Hi !
I tried to insert a script element in the page with the fucntion execute_script but nothing happens ! My element is not created.
sb.execute_script("var myscript = document.createElement('script');myscript.appendChild(document.createTextNode('//Test'));document.body.append(myscript);") sb.activate_cdp_mode(current_url)

i also tried with cdp.reload and script_to_evaluate_on_load but same result !
sb.cdp.reload(script_to_evaluate_on_load="var myscript = document.createElement('script');myscript.appendChild(document.createTextNode('//Test'));document.body.append(myscript);")

Can you help me ?
Thanks

You must be logged in to vote

Would be similar to how a button is added, as in #1429 (comment):

from seleniumbase import SB
with SB() as sb:
 script_to_add_button = """function injectButton() {
 var new_button=document.createElement('button');
 document.getElementsByTagName('body')[0].appendChild(new_button);
 new_button.style="width: 200px; height: 120px";
 }
 injectButton();"""
 sb.execute_script(script_to_add_button)
 sb.sleep(3)

Replies: 2 comments 3 replies

Comment options

Would be similar to how a button is added, as in #1429 (comment):

from seleniumbase import SB
with SB() as sb:
 script_to_add_button = """function injectButton() {
 var new_button=document.createElement('button');
 document.getElementsByTagName('body')[0].appendChild(new_button);
 new_button.style="width: 200px; height: 120px";
 }
 injectButton();"""
 sb.execute_script(script_to_add_button)
 sb.sleep(3)
You must be logged in to vote
2 replies
Comment options

Thanks !
I will try this solution.

If the url is redirected, will the button disappear?

Comment options

The button (and the rest of the page) is gone if there's a redirect after you call that.

Answer selected by mdmintz
Comment options

And can i do the same thing with parameter script_to_evaluate_on_load for the reload function ?

You must be logged in to vote
1 reply
Comment options

That’s one of the options. You can try that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants

AltStyle によって変換されたページ (->オリジナル) /