我想编写一个扩展,以替换HTML输入元素中的字符串。因此,当您单击弹出窗口时,它应将所有的'字符替换为\'。
这是manifest.json文件:
// opens a communication port
chrome.runtime.onConnect.addListener(function(port) {
// listen for every message passing throw it
port.onMessage.addListener(function(o) {
// if the message comes from the popup
if (o.from && o.from === 'popup' && o.start && o.start === 'Y') {
// inserts a script into your tab content
chrome.tabs.executeScript(null, {
// the script will click the button into the tab content
code: "document.getElementById('header').value = document.getElementById('header').value.replace(/'/g, '\\\''); console.log(document.getElementById('header').value);"
});
}
});
});
这是后台脚本:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<a id="popupBtn">Click me</a>
</body>
</html>
我不知道您是否需要它,但这是popup.html:
// always waits the document to be loaded when shown
document.addEventListener('DOMContentLoaded', function() {
// opens a communication between scripts
var port = chrome.runtime.connect();
// listens to the click of the button into the popup content
document.getElementById('popupBtn').addEventListener('click', function() {
// sends a message throw the communication port
port.postMessage({
'from': 'popup',
'start': 'Y'
});
});
});
它看起来像这样:
基本上,您单击弹出窗口,它会调用popup.js文件,该文件将消息发送到background.js文件。
...和popup.js文件:
def first_contains_second(word1, word2):
if word1 in word2:
return True
return False
def one_contains_another(word1, word2):
if word1 in word2 or word2 in word1:
return True
return False
代码获得ID为“ header”的元素的值,但未替换该值。当我将其插入输入字段中时:
我点击弹出窗口,它应该返回以下内容:asdfasdf \'adsfa \'asdf \'
这是控制台记录的内容: