Skip to content

Instantly share code, notes, and snippets.

@skairunner
Last active November 10, 2017 06:20
Show Gist options
  • Save skairunner/ab7a9b848190c8d8584a6bdd374b1700 to your computer and use it in GitHub Desktop.
Save skairunner/ab7a9b848190c8d8584a6bdd374b1700 to your computer and use it in GitHub Desktop.
Find and replace links chrome.extension
"use strict";
var links = document.querySelectorAll("a");
for (let link of links) {
let parent = link.parentElement;
let newel = document.createElement("span");
newel.innerHTML = link.innerHTML;
parent.replaceChild(newel, link);
chrome.runtime.sendMessage({
link: newel.getAttribute("href"),
text: newel.innerHTML
});
}
{
"manifest_version": 2,
"name": "Link Remover",
"description": "Removes all links from page.",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
]
}
<!doctype html>
<!--
This page is shown when the extension button is clicked, because the
"browser_action" field in manifest.json contains the "default_popup" key with
value "popup.html".
-->
<html>
<head>
<title>Getting Started Extension's Popup</title>
<style type="text/css">
button {
font-size: 14;
width: 100pt;
height:20pt;
}
.result {
display: block;
font-size: 14;
line-height: 1.5;
}
</style>
<!--
- JavaScript and HTML must be in separate files: see our Content Security
- Policy documentation[1] for details and explanation.
-
- [1]: https://developer.chrome.com/extensions/contentSecurityPolicy
-->
<script src="popup.js"></script>
</head>
<body>
<button>Remove links</button>
<div id="All Links"></div>
</body>
</html>
document.addEventListener('DOMContentLoaded', () => {
let outputDiv = document.querySelector("div");
// listen for messages from the child
chrome.runtime.onMessage.addListener(
// request: the content of the message
// sender: which tab sent the message
// sendResponse: an optional callback to respond to the message
function(request, sender, sendResponse) {
let child = document.createElement("a");
child.innerHTML = request.text;
child.className = "result";
child.setAttribute("href", request.link);
outputDiv.appendChild(child);
});
// on click
document.querySelector("button").addEventListener("click", () => {
// runs the given script in the active tab
chrome.tabs.executeScript({
file: "findAndReplace.js"
}, () => { // throws errors instead of silencing them
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
}
});
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment