nsIWebBrowserPersist 编辑

embedding/components/webbrowserpersist/nsIWebBrowserPersist.idlScriptable Interface for persisting DOM documents and URIs to local or remote storage. Inherits from: nsICancelable Last changed in Gecko 36.0 (Firefox 36.0 / Thunderbird 36.0 / SeaMonkey 2.33)

Implemented by: @mozilla.org/embedding/browser/nsWebBrowser;1 and @mozilla.org/embedding/browser/nsWebBrowserPersist;1. To create an instance, use:

var webBrowserPersist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
                        .createInstance(Components.interfaces.nsIWebBrowserPersist);

Method overview

void cancelSave();
void saveChannel(in nsIChannel aChannel, in nsISupports aFile);
void saveDocument(in nsIDOMDocument aDocument, in nsISupports aFile, in nsISupports aDataPath, in string aOutputContentType, in unsigned long aEncodingFlags, in unsigned long aWrapColumn);
void saveURI(in nsIURI aURI, in nsISupports aCacheKey, in nsIURI aReferrer, in long aReferrerPolicy, in nsIInputStream aPostData, in string aExtraHeaders, in nsISupports aFile, in nsILoadContext aPrivacyContext);
void savePrivacyAwareURI(in nsIURI aURI, in nsISupports aCacheKey, in nsIURI aReferrer, in long aReferrerPolicy, in nsIInputStream aPostData, in string aExtraHeaders, in nsISupports aFile, in boolean aIsPrivate);

Attributes

AttributeTypeDescription
currentStateunsigned longCurrent state of the persister object. Read only.
persistFlagsunsigned longFlags governing how data is fetched and saved from the network. It is best to set this value explicitly unless you are prepared to accept the default values.
progressListenernsIWebProgressListenerCallback listener for progress notifications. The object that the embbedder supplies may also implement nsIInterfaceRequestor and be prepared to return nsIAuthPrompt or other interfaces that may be required to download data.
resultunsigned longValue indicating the success or failure of the persist operation. Read only.

Constants

ConstantValueDescription
PERSIST_FLAGS_NONE0No special persistence behavior.
PERSIST_FLAGS_FROM_CACHE1Only use cached data (could result in failure if data is not cached).
PERSIST_FLAGS_BYPASS_CACHE2Bypass the cached data.
PERSIST_FLAGS_IGNORE_REDIRECTED_DATA4Ignore any redirected data (usually adverts).
PERSIST_FLAGS_IGNORE_IFRAMES8Ignore iframe content (usually adverts).
PERSIST_FLAGS_NO_CONVERSION16Do not run the incoming data through a content converter for example to decompress it.
PERSIST_FLAGS_REPLACE_EXISTING_FILES32Replace existing files on the disk (use with due diligence!)
PERSIST_FLAGS_NO_BASE_TAG_MODIFICATIONS64Don't modify or add base tags.
PERSIST_FLAGS_FIXUP_ORIGINAL_DOM128Make changes to original DOM rather than cloning nodes.
PERSIST_FLAGS_FIXUP_LINKS_TO_DESTINATION256Fix links relative to destination location (not origin)
PERSIST_FLAGS_DONT_FIXUP_LINKS512Do not make any adjustments to links.
PERSIST_FLAGS_SERIALIZE_OUTPUT1024Force serialization of output (one file at a time; not concurrent)
PERSIST_FLAGS_DONT_CHANGE_FILENAMES2048Don't make any adjustments to filenames.
PERSIST_FLAGS_FAIL_ON_BROKEN_LINKS4096Fail on broken in-line links.
PERSIST_FLAGS_CLEANUP_ON_FAILURE8192Automatically cleanup after a failed or cancelled operation, deleting all created files and directories. This flag does nothing for failed upload operations to remote servers.
PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION16384Let the WebBrowserPersist decide whether the incoming data is encoded and whether it needs to go through a content converter, for example to decompress it.
PERSIST_FLAGS_APPEND_TO_FILE32768Append the downloaded data to the target file. This can only be used when persisting to a local file.
PERSIST_FLAGS_FORCE_ALLOW_COOKIES65536Force relevant cookies to be sent with this load even if normally they wouldn't be.
PERSIST_STATE_READY1Persister is ready to save data.
PERSIST_STATE_SAVING2Persister is saving data.
PERSIST_STATE_FINISHED3Persister has finished saving data.
ENCODE_FLAGS_SELECTION_ONLY1Output only the current selection as opposed to the whole document.
ENCODE_FLAGS_FORMATTED2For plain text output. Convert html to plain text that looks like the html. Implies wrap (except inside <pre>), since html wraps. HTML output: always do prettyprinting, ignoring existing formatting.
ENCODE_FLAGS_RAW4Output without formatting or wrapping the content. This flag may be used to preserve the original formatting as much as possible.
ENCODE_FLAGS_BODY_ONLY8Output only the body section, no HTML tags.
ENCODE_FLAGS_PREFORMATTED16Wrap even if when not doing formatted output (for example for text fields).
ENCODE_FLAGS_WRAP32Wrap documents at the specified column.
ENCODE_FLAGS_FORMAT_FLOWED64For plain text output. Output for format flowed (RFC 2646). This is used when converting to text for mail sending. This differs just slightly but in an important way from normal formatted, and that is that lines are space stuffed. This can't (correctly) be done later.
ENCODE_FLAGS_ABSOLUTE_LINKS128Convert links to absolute links where possible.
ENCODE_FLAGS_ENCODE_W3C_ENTITIES256Attempt to encode entities standardized at W3C (HTML, MathML, and so on.). This is a catch-all flag for documents with mixed contents. Beware of interoperability issues. See below for other flags which might likely do what you want.
ENCODE_FLAGS_CR_LINEBREAKS512Output with carriage return line breaks. May also be combined with ENCODE_FLAGS_LF_LINEBREAKS and if neither is specified, the platform default format is used.
ENCODE_FLAGS_LF_LINEBREAKS1024Output with linefeed line breaks. May also be combined with ENCODE_FLAGS_CR_LINEBREAKS and if neither is specified, the platform default format is used.
ENCODE_FLAGS_NOSCRIPT_CONTENT2048For plain text output. Output the content of noscript elements.
ENCODE_FLAGS_NOFRAMES_CONTENT4096For plain text output. Output the content of noframes elements.
ENCODE_FLAGS_ENCODE_BASIC_ENTITIES8192Encode basic entities, for example output   instead of character code 0xa0. The basic set is just   & < > " for interoperability with older products that don't support α and friends.
ENCODE_FLAGS_ENCODE_LATIN1_ENTITIES16384Encode Latin1 entities. This includes the basic set and accented letters between 128 and 255.
ENCODE_FLAGS_ENCODE_HTML_ENTITIES32768Encode HTML4 entities. This includes the basic set, accented letters, Greek letters and certain special markup symbols.

Methods

cancelSave()

Cancels the current operation. The caller is responsible for cleaning up partially written files or directories. This has the same effect as calling cancel with an argument of NS_BINDING_ABORTED.

void cancelSave();
Parameters

None.

saveChannel()

Save a channel to a file. It must not be opened yet.

void saveChannel(
  in nsIChannel aChannel,
  in nsISupports aFile
);
Parameters
aChannel
The nsIChannel to save to a file.
aFile
Target local file. This may be a nsILocalFile object or an nsIURI object with a file scheme.

saveDocument()

Save the specified DOM document to file and optionally all linked files (for example images, CSS, JS & subframes). Do not call this method until the document has finished loading!

void saveDocument(
  in nsIDOMDocument aDocument,
  in nsISupports aFile,
  in nsISupports aDataPath,
  in string aOutputContentType,
  in unsigned long aEncodingFlags,
  in unsigned long aWrapColumn
);
Parameters
aDocument
Document to save to file. Some implementations of this interface may also support nsnull to imply the currently loaded document.
aFile
Target local file. This may be a nsILocalFile object or an nsIURI object with a file scheme or a scheme that supports uploading (for example ftp).
aDataPath
Path to directory where URIs linked to the document are saved or nsnull if no linked URIs should be saved. This may be a nsILocalFile object or an nsIURI object with a file scheme.
aOutputContentType
The desired MIME type format to save the document and all sub-documents into or nsnull to use the default behavior.
aEncodingFlags
Flags to pass to the encoder.
aWrapColumn
For text documents, indicates the desired width to wrap text at. Parameter is ignored if wrapping is not specified by the encoding flags.
Exceptions thrown
NS_ERROR_INVALID_ARG
One or more arguments was invalid.

saveURI()

As of Firefox 26, this method should no longer be used from add-on code. Please use Downloads.createDownload() instead.

As of Firefox 36, a new parameter aReferrerPolicy was added as the fourth argument, changing the number of parameters from 7 to 8 and shifting the order of the parameters in a backwards incompatible way.

Save the specified URI to file.

void saveURI(
  in nsIURI aURI,
  in nsISupports aCacheKey,
  in nsIURI aReferrer,
  in long aReferrerPolicy,
  in nsIInputStream aPostData,
  in string aExtraHeaders,
  in nsISupports aFile,
  in nsILoadContext aPrivacyContext
);
Parameters
aURI
URI to save to file. Some implementations of this interface may also support nsnull to imply the currently loaded URI.
aCacheKey
An object representing the URI in the cache or nsnull. This can be a necko cache key, an nsIWebPageDescriptor, or the currentDescriptor of an nsIWebPageDescriptor.
aReferrer
The referrer URI to pass with an HTTP request or nsnull.
aReferrerPolicy
The referrer policy to use for the request, taken from nsIHttpChannel.
aPostData
Post data to pass with an HTTP request or nsnull.
aExtraHeaders
Additional headers to supply with an HTTP request or nsnull.
aFile
Target file. This may be a nsILocalFile object or an nsIURI object with a file scheme or a scheme that supports uploading (for example ftp).
aPrivacyContext
A context derived from a relevant window or document (eg. the window containing a link being saved) via a docshell that QIs to nsILoadContext. Used to ensure that privacy-sensitive operations (such as saving a URI related to a private browsing session) do not leak any information (eg. cookies, permanent cache, etc.) Null must only be passed in the event that no such relevant context exists (ie. the URI being saved is unrelated to any current browsing session).

Important: If you think that you should be passing null here, you are almost certainly wrong. null should be passed only when no plausible privacy context exists for the URI to be saved, which is an exceedingly rare corner case.

Exceptions thrown
NS_ERROR_INVALID_ARG
One or more arguments was invalid.

savePrivacyAwareURI()

Save the specified URI to file, explicitly dictating whether the operation should be considered private for the purposes of network requests, caching, etc. All arguments and exceptions are identical to saveURI, with the exception of aIsPrivate which is used to indicate the private nature of the operation.

Example

function downloadFile(httpLoc, sourceWindow) {
  try {
    //new obj_URI object
    var obj_URI = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService).newURI(httpLoc, null, null);

    //new file object
    var obj_TargetFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);

    //set file with path
    obj_TargetFile.initWithPath("c:\\temp\\test.pdf");
    //if file doesn't exist, create
    if(!obj_TargetFile.exists()) {
      obj_TargetFile.create(0x00,0644);
    }

    //new persistence object
    var obj_Persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Components.interfaces.nsIWebBrowserPersist);

    // with persist flags if desired
    const nsIWBP = Components.interfaces.nsIWebBrowserPersist;
    const flags = nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
    obj_Persist.persistFlags = flags | nsIWBP.PERSIST_FLAGS_FROM_CACHE;

    var privacyContext = sourceWindow.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                                     .getInterface(Components.interfaces.nsIWebNavigation)
                                     .QueryInterface(Components.interfaces.nsILoadContext);

    //save file to target
    obj_Persist.saveURI(obj_URI,null,null,null,null,obj_TargetFile,privacyContext);
    // Starting with Firefox 36 saveURI takes 8 parameters when called. aReferrerPolicy was added.
    // obj_Persist.saveURI(obj_URI,null,null,null,null,null,obj_TargetFile,privacyContext);
  } catch (e) {
    alert(e);
  }
}

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:111 次

字数:21063

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文