如何在Firefox扩展中正确使用insertAdjacentHTML插入Achavi按钮到OSM变更集页面
Let's get your Firefox extension working correctly to add that Achavi button right where you want it in the OSM changeset sidebar. Here's what was off in your code and how to fix it:
Problem Breakdown
Your current code tries to pass a DOM element (zNode) to insertAdjacentHTML, but this method expects an HTML string instead. Additionally, the inline onclick syntax had quote escaping issues, and we can streamline how you target the sidebar section.
Corrected Code
manifest.json (no changes needed here)
{ "manifest_version": 2, "name": "modify-page", "version": "1.0", "content_scripts": [ { "matches": ["https://www.openstreetmap.org/changeset/*"], "js": ["achavi-insert.js"] } ] }
achavi-insert.js (fixed version)
// Extract the changeset ID from the URL const address = document.location.href; const match = address.match(/changeset\/([0-9]+)/); if (!match) return; // Exit if we're not on a valid changeset page const changesetId = match[1]; // Target the left sidebar section const sidebarSection = document.getElementById('browse-section'); if (!sidebarSection) return; // Create the button HTML string const achaviButtonHtml = ` <div id="achavi" style="margin: 10px 0;"> <button type="button" style="padding: 6px 12px; cursor: pointer;">Achavi Visualization</button> </div> `; // Insert the button right after the browse section in the sidebar sidebarSection.insertAdjacentHTML('afterend', achaviButtonHtml); // Add click event listener to the button (cleaner than inline onclick) const achaviButton = document.querySelector('#achavi button'); achaviButton.addEventListener('click', () => { window.open(`https://overpass-api.de/achavi/?changeset=${changesetId}`, '_blank'); });
Key Fixes & Explanations
insertAdjacentHTMLUsage: Instead of creating a DOM element first, we pass the raw HTML string directly toinsertAdjacentHTML. The'afterend'position places the button immediately after the#browse-sectionelement, keeping it in the left sidebar flow. If you want it inside the browse section, swap this with'beforeend'.- Event Listener Over Inline
onclick: UsingaddEventListeneravoids messy quote escaping and makes your code more maintainable. We also open the link in a new tab with_blankfor a better user experience. - Error Checking: Added checks to ensure we only run the code if we find the changeset ID and target sidebar element—prevents console errors if the page structure changes.
- Basic Styling: Added minimal inline styles to make the button fit better with OSM's existing sidebar design (feel free to tweak these as needed).
Testing the Extension
- Load your extension in Firefox via
about:debugging> "This Firefox" > "Load Temporary Add-on" - Navigate to any OSM changeset page (e.g., a sample changeset page)
- You should see the Achavi button in the left sidebar, right after the browse section.
内容的提问来源于stack exchange,提问作者Tanner Steinbuch
相关产品推荐
相关产品推荐

