1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "nsDOMSerializer.h"
9 #include "mozilla/Encoding.h"
10 #include "mozilla/dom/Document.h"
11 #include "nsIDocumentEncoder.h"
12 #include "nsComponentManagerUtils.h"
13 #include "nsContentUtils.h"
17 using namespace mozilla
;
19 nsDOMSerializer::nsDOMSerializer() = default;
21 static already_AddRefed
<nsIDocumentEncoder
> SetUpEncoder(
22 nsINode
& aRoot
, const nsAString
& aCharset
, ErrorResult
& aRv
) {
23 nsCOMPtr
<nsIDocumentEncoder
> encoder
=
24 do_createDocumentEncoder("application/xhtml+xml");
26 aRv
.Throw(NS_ERROR_FAILURE
);
30 dom::Document
* doc
= aRoot
.OwnerDoc();
31 bool entireDocument
= (doc
== &aRoot
);
33 // This method will fail if no document
34 nsresult rv
= encoder
->NativeInit(
35 doc
, u
"application/xhtml+xml"_ns
,
36 nsIDocumentEncoder::OutputRaw
|
37 nsIDocumentEncoder::OutputDontRewriteEncodingDeclaration
);
44 NS_ConvertUTF16toUTF8
charset(aCharset
);
45 if (charset
.IsEmpty()) {
46 doc
->GetDocumentCharacterSet()->Name(charset
);
48 rv
= encoder
->SetCharset(charset
);
54 // If we are working on the entire document we do not need to
55 // specify which part to serialize
56 if (!entireDocument
) {
57 rv
= encoder
->SetNode(&aRoot
);
65 return encoder
.forget();
68 void nsDOMSerializer::SerializeToString(nsINode
& aRoot
, nsAString
& aStr
,
72 if (!nsContentUtils::CanCallerAccess(&aRoot
)) {
73 aRv
.Throw(NS_ERROR_DOM_SECURITY_ERR
);
77 nsCOMPtr
<nsIDocumentEncoder
> encoder
= SetUpEncoder(aRoot
, u
""_ns
, aRv
);
82 nsresult rv
= encoder
->EncodeToString(aStr
);
88 void nsDOMSerializer::SerializeToStream(nsINode
& aRoot
,
89 nsIOutputStream
* aStream
,
90 const nsAString
& aCharset
,
92 if (NS_WARN_IF(!aStream
)) {
93 aRv
.Throw(NS_ERROR_INVALID_ARG
);
97 // The charset arg can be empty, in which case we get the document's
98 // charset and use that when serializing.
100 // No point doing a CanCallerAccess check, because we can only be
101 // called by system JS or C++.
102 nsCOMPtr
<nsIDocumentEncoder
> encoder
= SetUpEncoder(aRoot
, aCharset
, aRv
);
107 nsresult rv
= encoder
->EncodeToStream(aStream
);