~jhn/pwd.re

pwd.re/plugins/check_links.lua -rw-r--r-- 2.0 KiB
5c83d679 — Johan Add "title" to the h1 tags 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
--
-- Author: johan@pwd.re
-- Version: 1.0
--
-- This work is licensed under the terms of the MIT license.
-- For a copy, see <https://opensource.org/licenses/MIT>.
--
-- This widget get all anchor tags (links) in a HTML document and check whether
-- it is a external link (to another domain) or internal (within the same domain).
--
-- If the link points to another domain the widget makes sure the rel attribute
-- is set to "noopener noreferrer" (appending if necessary) and that the target
-- attribute it set to "_blank".
--
-- Use the widget by copying this file to the plugins/ directory and adding this
-- to soupault.conf:
--
-- [widgets.check-links]
--   widget = "check_links"
--
--
-- Caveats/bugs:
--   - The widget is not aware of the local domain being used, so a link to
--     https://<yourdomain> will be treated as an external link.
--   - The widget does not check if the properties we want to append to an
--     existing "rel" attribute already exists. If the property already exists
--     a duplicate will be added.
--

-- Get all a tags on the page
links = HTML.select(page, "a")

-- Loop through all the a tags
index = 1
while links[index] do
  link = links[index]

  -- Get the href attribute
  href = HTML.get_attribute(link, "href")

  -- If the link is external we will check for further attributes
  if Regex.match(href, "^http(s?)://") ~= nil then
    -- Check for the rel attribute
    rel_attrib = HTML.get_attribute(link, "rel")

    if rel_attrib ~= nil then
      -- "rel_attrib" is not nil so there is a "rel" attribute and we want to append to it
      HTML.set_attribute(link, "rel", HTML.get_attribute(link, "rel") .. " noopener")
    else
      -- "rel_attrib" is nil so we just set it without caring about appending
      HTML.set_attribute(link, "rel", "noopener")
    end

    -- Check and fix the target attribute
    if HTML.get_attribute(link, "target") ~= "_blank" then
      HTML.set_attribute(link, "target", "_blank")
    end
  end

  index = index + 1
end