gpt4 book ai didi

javascript - 从 Chrome 扩展程序写入网页的文本字段

转载 作者:行者123 更新时间:2023-12-02 18:08:58 26 4
gpt4 key购买 nike

我想创建一个 chrome 扩展程序,它接受一些文本,然后打开一个网站,并尝试将该文本写入文本字段。这就是我所拥有的:

chrome.omnibox.onInputEntered.addListener(
function(text) {
chrome.tabs.create({url:"http://www.editpad.org/"});
document.getElementById("text").value = txt; //.innerHTML = txt
alert('You just typed "' + text + '"');
});

我通过检查元素获得了 ID。我需要做什么才能这样写?

最佳答案

您的代码在(不可见的)background 的上下文中运行或event page 。为了“切换”到刚刚打开的页面的执行上下文,您需要使用 content script (以编程方式“即时”,使用 chrome.tabs.executeScript )。

下面带注释的代码显示了如何实现您想要的结果。

chrome.omnibox.onInputEntered.addListener(function(text) {
chrome.tabs.create({
url: 'http://www.editpad.org/'
}, function(tab) {
// chrome.tabs.executeScript takes a string that will be parsed and run
// as JavaScript code. To pass a string, you need to make sure that it
// does not contain any invalid characters. This can easily be achieved
// by serializing the input string to JSON.
var serializedValue = JSON.stringify(text);

chrome.tabs.executeScript(tab.id, {
code: 'document.getElementById("text").value = ' + serializedValue,
}, function(result) {
if (!result) {
// This usually happens when you do not have the permission to
// run code in the page. Add the site to the "permissions"
// section manifest.json.
alert('Failed to run content script.\n' +
chrome.runtime.lastError.message);
return;
}
// The value of the last expression is passed to the callback of
// chrome.tabs.executeScript, for each frame. The code runs only in
// the top-level frame (because `allFrames: true` is not specified),
// so the result is an array with only one element.
alert('You just typed: "' + result[0] + '"');
});
});
});

关于javascript - 从 Chrome 扩展程序写入网页的文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19867970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com