简体   繁体   English

使用Python将Javascript注入网页

[英]Inject Javascript into web page with Python

For my application I need to inject JS into the loaded url. 对于我的应用程序,我需要将JS注入加载的URL。

I am using the following snippet from here https://stackoverflow.com/a/10866495/1162305 我在这里使用以下代码片段https://stackoverflow.com/a/10866495/1162305

import wx 
import wx.html2 

class MyBrowser(wx.Dialog): 
  def __init__(self, *args, **kwds): 
    wx.Dialog.__init__(self, *args, **kwds) 
    sizer = wx.BoxSizer(wx.VERTICAL) 
    self.browser = wx.html2.WebView.New(self) 
    sizer.Add(self.browser, 1, wx.EXPAND, 10) 
    self.SetSizer(sizer) 
    self.SetSize((700, 700)) 

if __name__ == '__main__': 
  app = wx.App() 
  dialog = MyBrowser(None, -1) 
  dialog.browser.LoadURL("http://www.google.com") 
  dialog.Show() 
  dialog.browser.RunScript('alert("hello");')
  app.MainLoop() 

Here I am injecting javascript with RunScript but the problem is, this javascript loads before the webpage loads. 这里我用RunScript注入javascript,但问题是,这个javascript在网页加载之前加载。 How can I load this javascript after the webpage (given url) loaded completely. 如何在网页(给定网址)完全加载后加载此javascript。

I know in plain javascript I can use document.readyState === "complete", but here how can I do it? 我知道在普通的javascript中我可以使用document.readyState ===“complete”,但是我在这里该怎么做?

According to documentation: 根据文件:

http://wxpython.org/Phoenix/docs/html/html2.WebView.html#phoenix-title-asynchronous-notifications http://wxpython.org/Phoenix/docs/html/html2.WebView.html#phoenix-title-asynchronous-notifications

You should use EVT_WEBVIEW_LOADED event to check if asynchronous methods like LoadURL is completed. 您应该使用EVT_WEBVIEW_LOADED事件来检查是否已完成LoadURL等异步方法。

self.Bind(wx.html2.EVT_WEBVIEW_LOADED, self.OnWebViewLoaded, self.browser)

Complete code could look something like (not tested): 完整的代码看起来像(未经测试):

import wx 
import wx.html2 

class MyBrowser(wx.Dialog): 
  def __init__(self, *args, **kwds): 
    wx.Dialog.__init__(self, *args, **kwds) 
    sizer = wx.BoxSizer(wx.VERTICAL) 
    self.browser = wx.html2.WebView.New(self) 
    sizer.Add(self.browser, 1, wx.EXPAND, 10) 
    self.Bind(wx.html2.EVT_WEBVIEW_LOADED, self.OnWebViewLoaded, self.browser)
    self.SetSizer(sizer) 
    self.SetSize((700, 700))

  def OnWebViewLoaded(self, evt):
    # The full document has loaded
    self.browser.RunScript('alert("hello");')

if __name__ == '__main__': 
  app = wx.App() 
  dialog = MyBrowser(None, -1) 
  dialog.browser.LoadURL("http://www.google.com") 
  dialog.Show() 
  app.MainLoop() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM