【问题标题】:Execute web page js from chrome extension content script从 chrome 扩展内容脚本执行网页 js
【发布时间】:2013-03-09 05:05:45
【问题描述】:

我的网页html代码中有这个js函数。

function update() {
    document.getElementById( "textbox ").value = updatetext;
}

当我从 chrome 控制台执行“update()”时,它可以工作。
但是如果我从 chrome 扩展执行,

chrome.tabs.executeScript(tab.id, {code: "update();"}, function(result){});

它说没有定义更新。但如果我用“alert('ok')”替换,它就可以了。
然后我执行

eval("update()")

在 Chrome 扩展内容脚本中。它还说“未定义更新。”

那么我该怎么做才能在网页上调用js函数呢?

【问题讨论】:

标签: javascript google-chrome google-chrome-extension


【解决方案1】:

Chrome 在沙盒中执行内容脚本,因此需要注入内联脚本与网页交互:

var injectedCode = 'update()';
var script = document.createElement('script');
script.appendChild(document.createTextNode('('+ injectedCode +')();'));
(document.body || document.head || document.documentElement).appendChild(script);

【讨论】:

  • 谢谢,如果我想执行一个带有返回值的 js 函数?我怎样才能得到返回值? @KAdot
  • 您可以将返回值存储为隐藏 DOM 元素的成员,然后从内容脚本中读取。
  • 你能发布一个代码示例吗?我尝试了 document.documentElement.setAttribute(),但它只能设置 String 值,不适用于 js 对象。有什么方法可以返回一个 js 对象吗? @KAdot
  • 可以使用 JSON.stringify 返回对象。
  • 但是如果我想传递一个DOM元素,如何实现呢?@KAdot
猜你喜欢
  • 2015-12-24
  • 1970-01-01
  • 2012-05-09
  • 2019-11-05
  • 2018-12-03
  • 2016-02-24
  • 2020-06-13
  • 2011-04-25
  • 1970-01-01
相关资源
最近更新 更多