rehype.js plugin that automatically inserts Google Adsense (and theoretically any ad service) code.
This plugin inserts an ad code for each specified number of paragraphs. For example, insert Google Adsense display ad code every 5 paragraphs.
(Unlike Google Adsense's automatic ads) no ad code is inserted into blockquote or list items!
npm install rehype-auto-ads
import remarkParse from "remark-parse";
import rehypeStringify from "rehype-stringify";
import remarkRehype from "remark-rehype";
import { unified } from "unified";
import rehypeAutoAds from "rehype-auto-ads";
const options = {
adCode: "<AD_CODE>",
paragraphInterval: 2
};
const processor = unified()
.use(remarkParse)
.use(remarkRehype)
.use(rehypeAutoAds, options)
.use(rehypeStringify);
const markdown = `
# Hello, world!
This is a paragraph.
This is a paragraph.
This is a paragraph.
This is a paragraph.
`;
processor.process(markdown).then((result) => {
console.log(result.toString());
});
The above code will output the following:
<h1>Hello, world!</h1>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p><AD_CODE>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p><AD_CODE>
export interface RehypeAutoAdsOptions {
adCode: string;
countFrom?: number;
paragraphInterval?: number;
shouldInsertAd?: (
vfile: VFile,
previousNode: Root | ElementContent | Doctype,
nextNode: Root | ElementContent | Doctype | null,
ancestors: (Root | Element)[]
) => boolean;
}
The ad code to be inserted. For example, Google Adsense display ad code.
Initial value of paragraph counter. In other words, this value should be set to the value of paragraphInterval
minus the number of paragraphs you want to insert the first ad.
If you want to insert ad code from the third paragraph and every 5 paragraphs, set this to 2
.
Default: 0
The value indicating how many paragraphs to insert advertising code. For example, specifying 5 will insert ads every 5 paragraphs.
Default: 5
Function to determine whether to insert an ad code. If this function returns true
, the ad code will be inserted. The default implementation always returns true
.
vfile
: vfile of the current file.previousNode
: The previous node of the insertion point.nextNode
: The next node of the insertion point.ancestors
: Ancestors of thepreviousNode
.
npm install
npm run build
npm run format
npm run lint
npm run test
This repository uses Changesets to manage versioning and releases. When creating a pull request, please run the Changesets CLI and commit the changeset file.
npx changeset