JavaScript can not call content script JS function

依然范特西╮ 提交于 2019-12-04 19:24:58

Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.

See http://developer.chrome.com/extensions/content_scripts.html#execution-environment

I would suggest trying shared DOM to communicate between the content script and the page or Message Passing.

An example of code on the page would be:

function showDialog(url) {
    window.postMessage({
        type: "FROM_PAGE",
        text: url
    }, "*");
}

And in the contentscript:

// This function will NOT collide with showDialog of the page:
function showDialog(url) {
    /* ... */
}

window.addEventListener("message", function (event) {
    // We only accept messages from ourselves
    if (event.source != window) { return; }

    // Make sure we're looking at the correct event:
    if (event.data.type && (event.data.type == "FROM_PAGE")) {
        showDialog(event.data.text);
    }
}, false);

I haven't tested the above, so please consider it to be pseudocode. A similar example is available here: http://developer.chrome.com/extensions/content_scripts.html#host-page-communication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!