简体   繁体   中英

Google Chrome Extension: Passing javascript variable to iframe src

I have added "tabs" in permissions but this code doesnt work . The iframe works when the url is passed directly but not from the script.

    <html> 
    <head> 
    </head>
    <body >
    <iframe src="www" id="link" width="400" height="300">
    <p>Your browser does not support iframes.</p>
    </iframe>
    <script>
    var url1="xxx";
    chrome.tabs.getSelected(null,function(tab) {
    var url1= tab.url;
    });
    document.getElementById("link").src=url1;
    </script>
    </body>
    </html>

Let me see if I understand the question.

You would need to add to your content script manifest the permission to access that page that has the iframe. Once you do, you use Content Scripts and its Message Passing to pass data to that iframe.

In the example above, you would need to inject a content script, so in your manifest:

"content_scripts": [{
    "matches": ["https://www.my.injected.url/*"],
    "js": ["injected_script_that_has_the_iframe.js"],
    "run_at": "document_end",
    "all_frames": true
}]

Then in that content script, you can do normal JavaScript to set the URL:

document.getElementById("link").src= someURL;

Now, where is that URL coming from? Is it coming from your extension? If so, use Message Passing to request that.

chrome.extension.sendRequest({method: "GetURL"}, function(response) {
  document.getElementById("link").src= response.url;
});

And within your background page, you listen for requests coming from your background page:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if (request.method == "GetURL")
      sendResponse({url: "http://rim.com"});
    else
      sendResponse({}); // snub them.
});

To recap, your content script asks your extension (background page), what the URL is, and once it gets a response, it updates the iframe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM