[英]Writing to a webpage's textfield from chrome extension
我想創建一個帶有一些文本的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。 我需要做什么才能寫出來?
您的代碼在(不可見) 背景或事件頁面的上下文中運行。 為了“切換”到剛剛打開的頁面的執行上下文,您需要使用內容腳本 (以編程方式,“動態”,使用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] + '"');
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.