简体   繁体   English

从chrome扩展内容脚本执行网页js

[英]Execute web page js from chrome extension content script

I have this js function in my web page html code. 我在我的网页html代码中有这个js函数。

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

When I execute "update()" from chrome console, it works. 当我从chrome控制台执行“update()”时,它可以工作。
But if I execute from chrome extension, 但是如果我从chrome扩展程序执行,

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

It says update is not defined. 它说没有定义更新。 But if I replace with "alert('ok')", It works. 但如果我用“alert('ok')替换”,它就有效。
Then I execute 然后我执行

eval("update()")

in Chrome extension content script. 在Chrome扩展程序内容脚本中。 It also says "update is not defined." 它还说“未定义更新”。

So what can i do to call js function on web page? 那么我该怎么做才能在网页上调用js函数呢?

Chrome executes content scripts in a sandbox, so you need to inject an inline script to interact with the webpage: Chrome在沙箱中执行内容脚本,因此您需要注入内联脚本以与网页进行交互:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Chrome扩展程序-将数据从content_script.js返回到网页吗? - Chrome extension - pass data from content_script.js back to web page? chrome扩展通信网页-> content_script-> popup.js - chrome extension communication web page -> content_script -> popup.js Chrome扩展程序-如何在页面加载时执行JS脚本 - Chrome Extension - How to execute a JS script on page load Chrome 扩展 - 用于在任何页面上运行 js 的简单内容脚本 - Chrome Extension - Simple Content Script for running js on any page 与Chrome扩展程序中内容脚本中的页面脚本进行通信 - Communicate with a page script from a content script in a Chrome extension 从Chrome扩展程序内容脚本创建Web Worker - Create a Web Worker from a Chrome Extension content script 将选项页面中的设置交换为Chrome扩展程序中的内容脚本 - Exchanging Settings from Options Page to Content-Script in Chrome Extension 在Chrome扩展程序中从后台页面获取配置到内容脚本 - Get configs from background page to content script in chrome extension Chrome扩展程序-如何将DOM从内容脚本发送到后台页面? - Chrome Extension - How to message DOM from content script to background page? Chrome扩展程序-从内容脚本向事件页面发送变量 - Chrome Extension - Sending variable from content script to event page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM