pywebio / PyWebIO

Write interactive web app in script way.
https://pywebio.readthedocs.io
MIT License
4.54k stars 383 forks source link

How can I override the <head> tag for my page? #79

Closed ngshiheng closed 3 years ago

ngshiheng commented 3 years ago

Hi, may I know is there a way I can add some more <script> tags inside the <head> section of the default HTML>?

<!doctype html>
  | <html lang="">
  | <head>
  | <meta charset="UTF-8">
  | <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  | <title>Example</title>
  | <meta name="description" content="Foo bar">
  | <link rel="icon" type="image/png" sizes="32x32" 
 ...
  | <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/wang0618/PyWebIO-assets@v1.2.3/css/toastify.min.css">
  | <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/wang0618/PyWebIO-assets@v1.2.3/css/app.css">
  | </head>
 
<body>
  | <div class="pywebio">
wang0618 commented 3 years ago

If you want to include your javascript file, you can use the RequireJs built-in pywebio. If you only want to execute some js code, just use pywebio.session.run_js() function.

ngshiheng commented 3 years ago

What I wanted to do is to copy and paste the AdSense code in between the <head></head> tags of my site. This is the example code snippet that I want to include:

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxxx"
     crossorigin="anonymous"></script>
wang0618 commented 3 years ago

Does this work?

run_js("""
$('head').append('<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxxx"
     crossorigin="anonymous"></script>')
"""
ngshiheng commented 3 years ago

Thanks for the quick reply man. Just tried it out, it doesn't append the script tag inside , not even anywhere else

wang0618 commented 3 years ago

Sorry, a redundant linebreak was incorrectly added to the code, the correct code is:

run_js("""
$('head').append('<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxxx" crossorigin="anonymous"></script>')
"""

The above code does insert the script tag to head, you need use chrome's inspect panel to check the result rather than "View page source": image

ngshiheng commented 3 years ago

Oh yea, I see it now on the inspect panel. I kept looking from the page source. Thank you so much for your help. Let's see if Adsense works 🤞 Closing the issue now. Thanks.

Shahin-rmz commented 3 years ago

If you want to include your javascript file, you can use the RequireJs built-in pywebio.

do you have some examples or documentation about this? I'm not very familiar with frontend and JS and need some clue. To be specific, I'm looking for a way to have templates or themes for my PuWebIO website. (does not matter Bootstrap or Boilerplate JS) Thanks