#
hs.webview
Display web content in a window from Hammerspoon
This module uses Apple's WebKit WKWebView class to provide web content display with JavaScript injection support. The objective is to provide a functional interface to the WKWebView and WKUserContentController classes.
This module is not intended to replace a full web browser and does have some limitations to keep in mind:
- Self-signed SSL certificates are not accepted unless they have first been approved and included in the users Keychain by another method, for example, opening the page first in Safari.
- The context-menu (right clicking or ctrl-clicking in the webview) provides some menu items which are currently unsupported -- a known example of this is any "Download..." menu item in the context menu for links and images.
- It is uncertain at present exactly how or where cookies and cached page data is stored or how it can be invalidated.
- This can be mitigated to an extent for web requests by using
hs.webview:reload(true)
and by crafting the url forhs.webview:url({...})
as a table -- see the appropriate help entries for more information.
- This can be mitigated to an extent for web requests by using
Any suggestions or updates to the code to address any of these or other limitations as they may become apparent are welcome at the Hammerspoon github site: https://www.github.com/Hammerspoon/hammerspoon
#
Submodules
#
API Overview
Deprecateds - API features which will be removed in an future release
asHSDrawing asHSWindow setLevel
Constants - Useful values which cannot be changed
certificateOIDs windowMasks
Functions - API calls offered directly by the extension
titleVisibility
Constructors - API calls which return an object, typically one that offers API methods
new newBrowser
Methods - API calls which can only be made on an object returned by a constructor
allowGestures allowMagnificationGestures allowNavigationGestures allowNewWindows allowTextEntry alpha attachedToolbar behavior behaviorAsLabels bringToFront certificateChain children closeOnEscape darkMode delete deleteOnClose estimatedProgress evaluateJavaScript examineInvalidCertificates frame goBack goForward hide historyList hswindow html isOnlySecureContent isVisible level loading magnification navigationCallback navigationID orderAbove orderBelow parent policyCallback privateBrowsing reload sendToBack shadow show size sslCallback stopLoading title topLeft transparent url urlParts userAgent windowCallback windowStyle windowTitle
#
API Documentation
#
Deprecateds
#
asHSDrawing
#
asHSWindow
#
setLevel
#
Constants
#
certificateOIDs
#
windowMasks
#
Functions
#
titleVisibility
#
Constructors
#
new
| | |
| --------------------------------------------|-------------------------------------------------------------------------------------|
| Signature | hs.webview.new(rect, [preferencesTable], [userContentController]) -> webviewObject
|
| Type | Constructor |
| Description | Create a webviewObject and optionally modify its preferences. |
| Parameters |
rect
- a rectangle specifying where the webviewObject should be displayed.preferencesTable
- an optional table which can include one of more of the following keys:javaScriptEnabled
- JavaScript is enabled (default true)javaScriptCanOpenWindowsAutomatically
- can JavaScript open windows without user intervention (default true)minimumFontSize
- minimum font size (default 0.0)developerExtrasEnabled
- include "Inspect Element" in the context menusuppressesIncrementalRendering
- suppresses content rendering until fully loaded into memory (default false) The following additional preferences may also be set under OS X 10.11 or later (they will be ignored with a warning printed if used under OS X 10.10):applicationName
- a string specifying an application name to be listed at the end of the browser's USER-AGENT header. Note that this is only appended to the default user agent string; if you set a custom one withhs.webview:userAgent , this value is ignored.allowsAirPlay
- a boolean specifying whether media playback within the webview can play through AirPlay devices.datastore
- anhs.webview.datastore
object specifying where website data such as cookies, cacheable content, etc. is to be stored.privateBrowsing
- a boolean (default false) specifying that the datastore should be set to a new, empty and non-persistent datastore. Note that this will override thedatastore
key if both are specified and this is set to true.userContentController
- an optionalhs.webview.usercontent
object to provide script injection and JavaScript messaging with Hammerspoon from the webview.
- The webview object
- To set the initial URL, use the
hs.webview:url
method before showing the webview object. - Preferences can only be set when the webview object is created. To change the preferences of an open webview, you will need to close it and recreate it with this method.
- developerExtrasEnabled is not listed in Apple's documentation, but is included in the WebKit2 documentation.
#
newBrowser
#
Methods
#
allowGestures
#
allowMagnificationGestures
#
allowNavigationGestures
#
allowNewWindows
#
allowTextEntry
#
alpha
#
attachedToolbar
#
behavior
#
behaviorAsLabels
#
bringToFront
#
certificateChain
#
children
#
closeOnEscape
#
darkMode
#
delete
#
deleteOnClose
#
estimatedProgress
#
evaluateJavaScript
| | |
| --------------------------------------------|-------------------------------------------------------------------------------------|
| Signature | hs.webview:evaluateJavaScript(script, [callback]) -> webviewObject
|
| Type | Method |
| Description | Execute JavaScript within the context of the current webview and optionally receive its result or error in a callback function. |
| Parameters |
script
- the JavaScript to execute within the context of the current webview's displaycallback
- an optional function which should accept two parameters as the result of the executed JavaScript. The function parameters are as follows:result
- the result of the executed JavaScript code or nil if there was no result or an error occurred.error
- an NSError table describing any error that occurred during the JavaScript execution or nil if no error occurred.
- the webview object
#
examineInvalidCertificates
#
frame
#
goBack
#
goForward
#
hide
#
historyList
#
hswindow
#
html
#
isOnlySecureContent
#
isVisible
#
level
#
loading
#
magnification
#
navigationCallback
| | |
| --------------------------------------------|-------------------------------------------------------------------------------------|
| Signature | hs.webview:navigationCallback(fn) -> webviewObject
|
| Type | Method |
| Description | Sets a callback for tracking a webview's navigation process. |
| Parameters |
fn
- the function to be called when the navigation status of a webview changes. To disable the callback function, explicitly specify nil. The function should expect 3 or 4 arguments and may optionally return 1. The function arguments are defined as follows:action
- a string indicating the webview's current status. It will be one of the following:didStartProvisionalNavigation
- a request or action to change the contents of the main frame has occurreddidReceiveServerRedirectForProvisionalNavigation
- a server redirect was received for the main framedidCommitNavigation
- content has started arriving for the main framedidFinishNavigation
- the webview's main frame has completed loading.didFailNavigation
- an error has occurred after content started arrivingdidFailProvisionalNavigation
- an error has occurred as or before content has started arrivingwebView
- the webview object the navigation is occurring for.navID
- a navigation identifier which can be used to link this event back to a specific request made by ahs.webview:url
,hs.webview:html
, orhs.webview:reload
method.error
- a table which will only be provided whenaction
is equal todidFailNavigation
ordidFailProvisionalNavigation
. If provided, it will contain at leas some of the following keys, possibly others as well:code
- a numerical value indicating the type of error code. This will mostly be of use to developers or in debugging and may be removed in the future.domain
- a string indicating the error domain of the error. This will mostly be of use to developers or in debugging and may be removed in the future.description
- a string describing the condition or problem that has occurred.reason
- if available, more information about what may have caused the problem to occur.
- The webview object
- The return value of the callback function is ignored except when the
action
argument is equal todidFailNavigation
ordidFailProvisionalNavigation
. If the return value when the action argument is one of these values is a string, it will be treated as html and displayed in the webview as the error message. If the return value is the boolean value true, then no change will be made to the webview (it will continue to display the previous web page). All other return values or no return value at all, if these navigation actions occur, will cause a default error page to be displayed in the webview.
#
navigationID
#
orderAbove
#
orderBelow
#
parent
#
policyCallback
| | |
| --------------------------------------------|-------------------------------------------------------------------------------------|
| Signature | hs.webview:policyCallback(fn) -> webviewObject
|
| Type | Method |
| Description | Sets a callback to approve or deny web navigation activity. |
| Parameters |
fn
- the function to be called to approve or deny web navigation activity. To disable the callback function, explicitly specify nil. The callback function will accept three or four arguments and must return 1 argument which will determine if the action is approved or denied. The first argument will specify the type of policy request and will determine the second and third arguments as follows:navigationAction
: This applies to any connection to a server or service which supplies content for the webview and occurs before any connection has actually been made.the second argument will be the webview this request originates from.the third argument will be a table about the navigation action requested and may contain any of the following keys:request
- a table containing the request for that generated this policy action request. Seehs.webview.url
for details on what keys may be present in this table.sourceFrame
- a table describing the frame in which the request occurred containing the following keys:mainFrame
- a boolean value indicating if this is the main view frame of the webview or notrequest
- a table containing the request for this frame. Seehs.webview.url
for details on what keys may be present in this table.targetFrame
- a table with the same keys assourceFrame
, but describing the target of the request, if it differs.buttonNumber
- a number indicating the mouse button pressed that initiated this action or 0 if no mouse button was involved (for example, a url specified viahs.webview.url
or a request for an image, etc. as part of rendering an earlier request).modifierFlags
- a table containing keys for the keyboard modifiers which were pressed when the navigation generating this policy request was generated.navigationType
- a string indicating how the navigation was requested:linkActivated
,formSubmitted
,backForward
,reload
,formResubmitted
, orother
The callback function should returntrue
if the navigation should proceed or false if it should be denied.navigationResponse
: This applies to any connection to a server or service which supplies content for the webview and occurs after the connection has been made but before it has been rendered in the webview.the second argument will be the webview this request originates from.the third argument will be a table about the response received and may contain any of the following keys:canShowMIMEType
- a boolean indicating whether or not the webview can display the content either natively or with a plugin. If this value is false, it is likely the content either cannot be displayed at all or will appear as gibberish in the webview.forMainFrame
- a boolean indicating if the response is for a navigation of the main frames primary content (i.e. not an image or sub-frame, etc.)response
- a table describing the response to the URL request and may contain any of the following keys:expectedContentLength
- the expected length of the response contentsuggestedFileName
- a suggested filename for the response dataMIMEType
- the MIME type of the response datatextEncodingName
- if the response is text, then this will contain the encoding type usedURL
- the URL of the actual response. Note that this may differ from the original request due to redirects, etc.statusCode
- the HTTP response code for the requeststatusCodeDescription
- a localized description of the response codeallHeaderFields
- a table containing the header fields and values provided in the response The callback function should returntrue
if the navigation should proceed or false if it should be denied.newWindow
: This applies to any request to create a new window from a webview. This includes JavaScript, the user selecting "Open in a new window", etc.the second argument will be the new webview this request is generating.the third argument will be a table about the navigation action requested. See the description above fornavigationAction
for details about this parameter.the fourth argument will be a table containing features requested for the new window (none of these will be addressed by default -- you can choose to honor or disregard the feature requests in the callback yourself) and may contain any of the following keys:menuBarVisibility
- Whether the menu bar should be visible. (Not a feature provided for windows under OS X)statusBarVisibility
- Whether the status bar should be visible. (Not currently supported by this module)toolbarsVisibility
- Whether toolbars should be visible.allowsResizing
- Whether the new window should be resizable.x
- The x coordinate of the new window.y
- The y coordinate of the new window.h
- The height coordinate of the new window.w
- The width coordinate of the new window. The callback function should returntrue
if the new window should be created or false if it should not.authenticationChallenge
: This applies to a web page which requires a log in credential for HTTPBasic or HTTPDigest authentication.the second argument will be the webview this request originates from.the third argument will be a table containing the challenge details and may contain any of the following keys:previousFailureCount
- an integer indicating the number of previously failed login attempts. This will be 0 for the first try.failureResponse
- the response data as described fornavigationResponse
above for the last authentication failureResponseproposedCredential
- a table containing the previously failed credential containing any of the following keys:hasPassword
- a boolean value indicating if a password was provided with this credentialpersistence
- a string value identifying the persistence of this credential. This value will be one of the following:None - the credential is for this URL request only and no othersession
- the credential is for this session and will be forgotten once the webview is deletedpermanent
- the credential is stored in the user's keychainsynchronized
- the credential is stored in the user's keychain and may be shared with other devices with the same owning Apple ID.user
- the username of the failed credentialpassword
- the password of the failed credentialprotectionSpace
- a table describing the realm for the authentication and may contain any of the following keys:port
- the port of the server with which communication for this request is occurringreceivesCredentialSecurely
- a boolean value indicating whether or not the credential can be sent to the server securelyauthenticationMethod
- a string indicating the authentication type: default, HTTPBasic, or HTTPDigest. Other types exists but are not currently supported with this module or do not apply to webview activities.host
- the host name of the server with which communication for this request is occurringprotocol
- the protocol for which the authentication is occurringisProxy
- a boolean indicating whether or not the authentication is occurring with a proxy serverproxyType
- a string representing the type of proxy server: http, https, ftp, or socks.realm
- a string representing the realm name for the authentication. The callback function should return true if the user should be prompted for the username and password credentials, a table with the keysuser
andpassword
containing the username and password to log in with, or false if the login request should be cancelled. Note that if your function returns a table and fails to authenticate three times, the user will be prompted anyways to prevent loops.
- The webview object
- With the
newWindow
action, the navigationCallback and policyCallback are automatically replicated for the new window from its parent. If you wish to disable these for the new window or assign a different set of callback functions, you can do so before returning true in the callback function with the webview argument provided.
#
privateBrowsing
#
reload
#
sendToBack
#
shadow
#
show
#
size
#
sslCallback
| | |
| --------------------------------------------|-------------------------------------------------------------------------------------|
| Signature | hs.webview:sslCallback(fn) -> webviewObject
|
| Type | Method |
| Description | Sets a callback to examine an invalid SSL certificate and determine if an exception should be granted. |
| Parameters |
fn
- the function to be called to examine the SSL certificate to determine if an exception should be granted. To disable the callback function, explicitly specify nil. The callback function will accept two arguments and must return 1 argument which will determine if the action is approved or denied. The first argument will be the webview this request originates from. The second argument will be a table containing the protection space details and may include the following keys:port
- the port of the server with which communication for this request is occurringreceivesCredentialSecurely
- a boolean value indicating whether or not the credential can be sent to the server securelyauthenticationMethod
- a string indicating the authentication type, in this case "serverTrust".host
- the host name of the server with which communication for this request is occurringprotocol
- the protocol for which the authentication is occurringisProxy
- a boolean indicating whether or not the authentication is occurring with a proxy serverproxyType
- a string representing the type of proxy server: http, https, ftp, or socks.realm
- a string representing the realm name for the authentication.certificates
- an array of tables, each table describing a certificate in the SSL certificate chain provided by the server responding to the webview's request. Each table will contain the following keys:commonName
- the common name for the certificate; most commonly this will be a string matching the server portion of the URL request or other descriptor of the certificate's purpose.values
- a table containing key-value pairs describing the certificate. The keys will be certificate OIDs. Common OIDs and their meaning can be found inhs.webview.certificateOIDs . The value for each key will be a table with the following keys:label
- a description or label for the entrylocalized label
- a localized version oflabel``type
- a description of the data type for this valuevalue
- the value
- The webview object
- The callback function should return true if an exception should be granted for this certificate or false if it should be rejected.
- even if this callback returns
true
, the certificate will only be granted an exception ifhs.webview:examineInvalidCertificates has also been set totrue
. - once an invalid certificate has been granted an exception, the exception will remain in effect until the webview object is deleted.
- the callback is only invoked for invalid certificates -- if a certificate is valid, or once an exception has been granted, the callback will not (no longer) be called for that certificate.
- * If the certificate has been granted an exception in another application which registers the exception in the user's keychain (e.g. Safari), then the certificate is no longer considered invalid and this callback will not be invoked.
#
stopLoading
#
title
#
topLeft
#
transparent
#
url
| | |
| --------------------------------------------|-------------------------------------------------------------------------------------|
| Signature | hs.webview:url([URL]) -> webviewObject, navigationIdentifier | url
|
| Type | Method |
| Description | Get or set the URL to render for the webview. |
| Parameters |
URL
- an optional string or table representing the URL to display. If you provide a table, it should contain one or more of the following keys (note that URL is the only required key):URL
- the URL of the desired contentmainDocumentURL
- the URL of the main document, if it differs. This usually only matters for cookie negotiation and currently has no effect in this module.HTTPBody
- the message body of the request, as in an HTTP POST requestHTTPMethod
- the HTTP Method of the request, default GET.timeoutInterval
- the timeout interval for the request in seconds, default 60.0.HTTPShouldHandleCookies
- whether or not cookies should be managed automatically, default true. Currently there is no support for the manual handling of cookies, though this may change in the future.HTTPShouldUsePipelining
- whether or not the request can continue to transmit data before receiving a response from the remote server. Default false.cachePolicy
- a string value representing the cache policy for the request. It should match one of the following:protocolCachePolicy
- (default) the cache policy defined as the default for the protocol of the URL requestignoreLocalCache
- ignore any locally cached content and request all content from the remote serverreturnCacheOrLoad
- return cached data, regardless of its age or expiration date. If there is no existing data in the cache corresponding to the request, load data from the originating source.returnCacheDontLoad
- treat the request as if offline - return cached data, regardless of its age or expiration date. If there is no existing data in the cache corresponding to the request, the load is considered to have failed.networkServiceType
- a string value representing the network service type of the request. It should match one of the following:default
- (default) standard network traffic. You should rarely use a value other than this as it can affect the responsiveness of your computer and other applications.VoIP
- with the VoIP service type, the kernel continues to listen for incoming traffic while your app is in the background, then wakes up your app whenever new data arrives. This should be used only for connections that are used to communicate with a VoIP service.video
- specifies that this is video trafficbackground
- use this for data if your are performing a download that was not requested by the user — for example, prefetching content so that it will be available when the user chooses to view it.voice
- specifies that this is voice trafficHTTPHeaderFields
- a table containing key-value pairs corresponding to additional headers you wish to include in your request. Because the HTTP specification requires that both keys and values are strings, any key which is not a string is ignored, and any value which is not a string or number is also ignored. In addition, the following keys are handled automatically behind the scenes and will be ignored if you specify them:Authorization``Connection``Host``WWW-Authenticate``Content-Length
- If a URL is specified, then this method returns the webview Object; otherwise it returns the current url being displayed.
- The networkServiceType field of the URL request table is a hint to the operating system about what the underlying traffic is used for. This hint enhances the system's ability to prioritize traffic, determine how quickly it needs to wake up the Wi-Fi radio, and so on. By providing accurate information, you improve the ability of the system to optimally balance battery life, performance, and other considerations. Likewise, inaccurate information can have a deleterious effect on your system performance and battery life.
#
urlParts
#
userAgent
#
windowCallback
| | |
| --------------------------------------------|-------------------------------------------------------------------------------------|
| Signature | hs.webview:windowCallback(fn) -> webviewObject
|
| Type | Method |
| Description | Set or clear a callback for updates to the webview window |
| Parameters |
fn
- the function to be called when the webview window is moved or closed. Specify an explicit nil to clear the current callback. The function should expect 2 or 3 arguments and return none. The arguments will be one of the following: "closing", webview - specifies that the webview window is being closed, either by the user or with thehs.webview:delete method.action
- in this case "closing", specifying that the webview window is being closedwebview
- the webview that is being closed "focusChange", webview, state - indicates that the webview window has either become or stopped being the focused windowaction
- in this case "focusChange", specifying that the webview window is being closedwebview
- the webview that is being closedstate
- a boolean, true if the webview has become the focused window, or false if it has lost focus "frameChange", webview, frame - indicates that the webview window has been moved or resizedaction
- in this case "focusChange", specifying that the webview window is being closedwebview
- the webview that is being closedframe
- a rect-table containing the new co-ordinates and size of the webview window
- The webview object
#
windowStyle
| | |
| --------------------------------------------|-------------------------------------------------------------------------------------|
| Signature | hs.webview:windowStyle(mask) -> webviewObject | currentMask
|
| Type | Method |
| Description | Get or set the window display style |
| Parameters |
- mask - if present, this mask should be a combination of values found in
hs.webview.windowMasks
describing the window style. The mask should be provided as one of the following: integer - a number representing the style which can be created by combining values found inhs.webview.windowMasks
with the logical or operator. string - a single key fromhs.webview.windowMasks
which will be toggled in the current window style. table - a list of keys fromhs.webview.windowMasks
which will be combined to make the final style by combining their values with the logical or operator.
- if a mask is provided, then the webviewObject is returned; otherwise the current mask value is returned.